t1.start(); t1.join(); t2.start();
沒有設置Timeout參數的Object.wait() 沒有設置Timeout參數的Thread.join() LockSupport.park()
Thread.sleep() 設置了Timeout參數的Object.wai() 設置了Timeout參數的Thread.join() LockSupport.parkNanos() LockSupport.parkUntil()
private volatile int a = 0; for (int x=0 ; x<=100 ; x++){ new Thread(new Runnable() { @Override public void run() { a++; Log.e("小楊逗比Thread-------------",""+a); } }).start(); }
for (int x=0 ; x<=100 ; x++){ new Thread(new Runnable() { @Override public void run() { AtomicInteger atomicInteger = new AtomicInteger(a++); int i = atomicInteger.get(); Log.e("小楊逗比Thread-------------",""+i); } }).start(); }
Synchronize做用於方法和靜態方法區別php
測試代碼以下所示html
private void test() { final TestSynchronized test1 = new TestSynchronized(); final TestSynchronized test2 = new TestSynchronized(); Thread t1 = new Thread(new Runnable() { @Override public void run() { test1.method01("a"); //test1.method02("a"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { test2.method01("b"); //test2.method02("a"); } }); t1.start(); t2.start(); }
private static class TestSynchronized{
private int num1;
public synchronized void method01(String arg) {
try {
if("a".equals(arg)){
num1 = 100;
System.out.println("tag a set number over");
Thread.sleep(1000);
}else{
num1 = 200;
System.out.println("tag b set number over");
}
System.out.println("tag = "+ arg + ";num ="+ num1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}java
private static int num2; public static synchronized void method02(String arg) { try { if("a".equals(arg)){ num2 = 100; System.out.println("tag a set number over"); Thread.sleep(1000); }else{ num2 = 200; System.out.println("tag b set number over"); } System.out.println("tag = "+ arg + ";num ="+ num2); } catch (InterruptedException e) { e.printStackTrace(); } }
}git
//調用method01方法打印日誌【普通方法】
tag a set number over
tag b set number over
tag = b;num =200
tag = a;num =100github
//調用method02方法打印日誌【static靜態方法】
tag a set number over
tag = a;num =100
tag b set number over
tag = b;num =200面試
- 在static方法前加synchronized:靜態方法屬於類方法,它屬於這個類,獲取到的鎖,是屬於類的鎖。 - 在普通方法前加synchronized:非static方法獲取到的鎖,是屬於當前對象的鎖。 [技術博客大總結](https://github.com/yangchong211/YCBlogs) - 結論:類鎖和對象鎖不一樣,synchronized修飾不加static的方法,鎖是加在單個對象上,不一樣的對象沒有競爭關係;修飾加了static的方法,鎖是加載類上,這個類全部的對象競爭一把鎖。