Java之synchronized

英文释义
/ˈsɪŋkrənaɪzd/
adj. 同步的;同步化的
v. 使协调(synchronize 的过去分词);同时发生;校准

作为Java关键字,是一种同步锁,可以修饰代码块、方法、静态方法、类。
作用于代码块和方法时,作用对象是其调用对象。
作用于静态方法和类时,作用对象时这个类的所有对象。

1、修饰代码块:一个线程在访问一个对象中的synchronized(this)同步代码块时,其他试图访问该对象的线程将被阻塞。

public class SyncTaskNew implements Runnable {

    private static int count = 0;

    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + count++);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        SyncTaskNew syncTask = new SyncTaskNew();
        Thread thread1 = new Thread(syncTask, "thread-1");
        Thread thread2 = new Thread(syncTask, "thread-2");
        thread1.start();
        thread2.start();
    }
}

thread-1:0
thread-1:1
thread-1:2
thread-1:3
thread-1:4
thread-2:5
thread-2:6
thread-2:7
thread-2:8
thread-2:9

你可能感兴趣的:(Java之synchronized)