執行緒同步機制 synchronized
阿新 • • 發佈:2018-12-20
JAVA中的鎖
在JAVA只有一種鎖,物件鎖。如果按照物件的型別細分,又分為例項物件鎖和Class物件
鎖。即我們常稱的,物件鎖與類鎖。
一把鑰匙開一把鎖
鎖的作用就是防止意外情況的發生,把門一鎖就是幹,幹完開鎖還鑰匙走人,下一個繼續
例項物件鎖
public class SyncInThread {
static class SyncInClassInstance implements Runnable {
private Integer a = 0;
@Override
public void run() {
_run ();
}
private synchronized void _run(){
a += 1;
System.out.println(Thread.currentThread().getName()+":a="+a);
}
}
public static void main(String[] args) throws InterruptedException {
SyncInClassInstance syncTest = new SyncInClassInstance () ;
Thread t1 = new Thread(syncTest) ;
t1.start();
Thread t2 = new Thread(syncTest) ;
t2.start();
Thread.sleep(1000);
}
}
**效果:**無論執行緒誰先誰後,物件裡a變數方法是按照順序來的
Thread-1:a=1
Thread-0:a=2
Process finished with exit code 0
類鎖【Class物件鎖】
public class SyncInThread {
static class SyncInClassInstance implements Runnable {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"正在獲取SyncTest類鎖");
_run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void _run() throws InterruptedException {
synchronized(SyncTest.class){
System.out.println(Thread.currentThread().getName()+"已獲取SyncTest類鎖");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"已釋放SyncTest類鎖");
}
}
}
public static void main(String[] args) throws InterruptedException {
SyncInClassInstance syncTest = new SyncInClassInstance() ;
Thread t1 = new Thread(syncTest) ;
t1.start();
SyncInClassInstance syncTest2 = new SyncInClassInstance() ;
Thread t2 = new Thread(syncTest2) ;
t2.start();
Thread.sleep(1000);
}
}
**效果:**本例以語句塊方式同步類物件,多個物件例項也要配對等鑰匙
Thread-0正在獲取SyncTest類鎖
Thread-1正在獲取SyncTest類鎖
Thread-1已獲取SyncTest類鎖
Thread-1已釋放SyncTest類鎖
Thread-0已獲取SyncTest類鎖
Thread-0已釋放SyncTest類鎖
Process finished with exit code 0