Java多執行緒synchronized與 lock同步及交替列印
阿新 • • 發佈:2018-12-28
synchronized與 lock
區別
1)Lock不是Java語言內建的,synchronized是Java語言的關鍵字。Lock是一個介面,通過這個介面的實現類可以實現同步訪問;
2)採用synchronized不需要手動釋放鎖,當synchronized方法或者synchronized程式碼塊執行完之後,系統會自動讓執行緒釋放對鎖的佔用;而Lock則必須要使用者去手動釋放鎖,如果沒有主動釋放鎖,就有可能導致出現死鎖現象。
使用synchronized同步交替列印-Runnable
package ThreadTest;
/**
* @author: Hongyuan Bai
* @create: 2018-12-27 14:13:39
* @description: 實現ruannable介面方式建立多執行緒
*/
public class Thread1 implements Runnable{
int sum = 200;
@Override
public void run() {
synchronized (this) {
while (sum > 0) {
try {
this.notify();
System.out.println(sum-- + Thread.currentThread().getName()) ;
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
使用synchronized同步交替列印-Thread類
package ThreadTest;
/**
* @author: Hongyuan Bai
* @create: 2018-12-28 09:50:44
* @description: 繼承Thread類方式建立多執行緒
*/
public class Thread2 extends Thread{
static int sum = 200;
Object obj;
public Thread2() {
}
public Thread2(Object obj) {
this.obj = obj;
}
@Override
public void run() {
synchronized (obj) {
while (sum > 0) {
try {
obj.notify();
System.out.println(sum-- + Thread.currentThread().getName());
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Lock實現同步
package ThreadTest;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author: Hongyuan Bai
* @create: 2018-12-28 10:54:42
* @description: Lock實現同步
*/
public class Thread3 implements Runnable{
int sum = 200;
Lock lock = new ReentrantLock();
@Override
public void run() {
lock.lock();
try {
while (sum > 0) {
System.out.println(sum-- + Thread.currentThread().getName());
}
} finally {
lock.unlock();
}
}
}