您好,登錄后才能下訂單哦!
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作用于方法和靜態方法區別
測試代碼如下所示
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();
}
}
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();
}
}
}
//調用method01方法打印日志【普通方法】
tag a set number over
tag b set number over
tag = b;num =200
tag = a;num =100
//調用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的方法,鎖是加載類上,這個類所有的對象競爭一把鎖。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。