synchronized是新同步的原因

1、synchronized是新同步的原因:队列与锁。

 

2、synchronized的使用:

1)利用方法实现:

/**
 * Desc: 线程代码块同步
 * 
 */
public class ThreadSyn implements Runnable{
    private  volatile static int count = 0;
    //  在run 方法前面加了synchronized
    @Override
    public synchronized void run() {
            for (int i = 0; i < 5; i++) {
                try {
                    System.out.println(Thread.currentThread().getName() + ":" + (count++));
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    }
}

2)利用代码块进行使用

class Test implements Runnable
{
   private byte[] lock = new byte[0];  // 特殊的instance变量
   public void method()
   {
      synchronized(lock) {
         // todo 同步代码块
      }
   }

   public void run() {

   }
}

 

posted @ 2020-05-24 12:51  jzhao1  阅读(41)  评论(0)    收藏  举报