Synchronized 关键字的用法


第一条:当一个线程访问某对象的synchronized方法或者synchronized代码块时,其他线程对该对象的该synchronized方法或者synchronized代码块的访问将被阻塞。

public class MoreThread {
    public static void main(String[] args) {
         Piao piao = new Piao();
         Thread t1 = new Thread(piao);
         Thread t2 = new Thread(piao);
         Thread t3 = new Thread(piao);
         t1.start();
         t2.start();
         t3.start();
    }
}

class Piao implements Runnable {
    @Override
    public void run() {
        /*synchronized(this) {*/
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + " 卖票:ticket " + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        /*}*/
    }
}

  没有加上synchronized:

Thread-1 卖票:ticket 0
Thread-0 卖票:ticket 0
Thread-2 卖票:ticket 0
Thread-1 卖票:ticket 1
Thread-0 卖票:ticket 1
Thread-2 卖票:ticket 1
Thread-1 卖票:ticket 2
Thread-0 卖票:ticket 2
Thread-2 卖票:ticket 2
Thread-1 卖票:ticket 3
Thread-0 卖票:ticket 3
Thread-2 卖票:ticket 3
Thread-0 卖票:ticket 4
Thread-2 卖票:ticket 4
Thread-1 卖票:ticket 4
Thread-2 卖票:ticket 5
Thread-0 卖票:ticket 5
Thread-1 卖票:ticket 5
Thread-1 卖票:ticket 6
Thread-2 卖票:ticket 6
Thread-0 卖票:ticket 6
Thread-1 卖票:ticket 7
Thread-0 卖票:ticket 7
Thread-2 卖票:ticket 7
Thread-1 卖票:ticket 8
Thread-0 卖票:ticket 8
Thread-2 卖票:ticket 8
Thread-1 卖票:ticket 9
Thread-2 卖票:ticket 9
Thread-0 卖票:ticket 9

  加上synchronized:这个代码块要等一个线程访问完成之后,另一个线程才能访问。

Thread-1 卖票:ticket 0
Thread-1 卖票:ticket 1
Thread-1 卖票:ticket 2
Thread-1 卖票:ticket 3
Thread-1 卖票:ticket 4
Thread-1 卖票:ticket 5
Thread-1 卖票:ticket 6
Thread-1 卖票:ticket 7
Thread-1 卖票:ticket 8
Thread-1 卖票:ticket 9
Thread-0 卖票:ticket 0
Thread-0 卖票:ticket 1
Thread-0 卖票:ticket 2
Thread-0 卖票:ticket 3
Thread-0 卖票:ticket 4
Thread-0 卖票:ticket 5
Thread-0 卖票:ticket 6
Thread-0 卖票:ticket 7
Thread-0 卖票:ticket 8
Thread-0 卖票:ticket 9
Thread-2 卖票:ticket 0
Thread-2 卖票:ticket 1
Thread-2 卖票:ticket 2
Thread-2 卖票:ticket 3
Thread-2 卖票:ticket 4
Thread-2 卖票:ticket 5
Thread-2 卖票:ticket 6
Thread-2 卖票:ticket 7
Thread-2 卖票:ticket 8
Thread-2 卖票:ticket 9

  


第二条:当一个线程访问某对象的synchronized方法或者synchronized代码块时,其他线程仍然可以访问该对象的非同步代码块。
第三条:当一个线程访问某对象的synchronized方法或者synchronized代码块时,其他线程对该对象的其他的synchronized方法或者synchronized代码块的访问将被阻塞。

猜你喜欢

转载自www.cnblogs.com/huoyufei/p/11287576.html