11 April 2017

Java Core: Synchronized Đồng bộ hóa sử dụng như thế nào và VD về Luồng

Đồng bộ hóa sử dụng như thế nào
Java Core 2017
package com.cakes;

public class SyncExample {

 public static void main(String[] args) {
  hello();
  goodbye();
 }

 public static synchronized void hello() {
  System.out.println("hello");
 }

 public static void goodbye() {
  synchronized (SyncExample.class) {
   System.out.println("goodbye");
  }
 }
}
Main.java
Java Core 2017
package demo;

public class Main {

    public static void main(String[] args) {
        Test test = new Test();
        Thread thread1 = new Thread(test);
        Thread thread2 = new Thread(test);
        thread1.setName("Demo1");
        thread2.setName("Demo2");
        thread1.start();
        thread2.start();

    }

}

class Test implements Runnable {

    int count = 1000;

    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1);
                System.out.println(Thread.currentThread().getName() + " " + count--);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Main.java
Java Core 2017
package demo;

public class Main {

    public static void main(String[] args) {
        Test test = new Test();
        Thread thread1 = new Thread(test);
        Thread thread2 = new Thread(test);
        thread1.setName("Demo1");
        thread2.setName("Demo2");
        thread1.start();
        thread2.start();

    }

}

class Test implements Runnable {

    int count = 1000;

    public synchronized void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1);
                System.out.println(Thread.currentThread().getName() + " " + count--);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Main.java
Java Core 2017
package demo;

public class Main {

    public static void main(String[] args) {
        Test test = new Test();
        Thread thread1 = new Thread(test);
        Thread thread2 = new Thread(test);
        thread1.setName("Demo1");
        thread2.setName("Demo2");
        thread1.start();
        thread2.start();

    }

}

class Test implements Runnable {

    int count = 1000;

    public void run() {
        synchronized (Main.class) {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1);
                    System.out.println(Thread.currentThread().getName() + " " + count--);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Synchronized là Đồng bộ hóa.
Hàm run() được gọi theo tuần tự, thread1 và thread2 cùng chạy nhưng nó không thể cùng 1 lúc gọi hàm run nếu có Synchronized

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang