7.Lock同步鎖
解決線程安全問題的方式,使用synchronize隐式鎖,1.同步代碼塊,2.同步方法,3.java5之後使用同步鎖Lock:顯示鎖,也就是說必須通過lock()方法上鎖,通過unlock()方法釋放鎖。
執行個體如下:
public class TestLock {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket, "1号視窗").start();
new Thread(ticket, "2号視窗").start();
new Thread(ticket, "3号視窗").start();
}
}
class Ticket implements Runnable {
private int tick = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock();// 上鎖
try {
if (tick > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "完成售票,餘票為:" + --tick);
}
} finally {
lock.unlock();//釋放鎖,那必須寫在finally中
}
}
}
}
使用lock如何實作等待-喚醒機制,執行個體為生産者消費者案例
什麼是虛假喚醒
在生産者和消費者中,生産者向店員提供商品,消費者向店員消費商品,在多個線程中同時生産和消費,就會出現一種情況就是不停的顯示缺貨,為了解決這個問題就是,如果店員沒有商品,那麼消費者消費的線程就等待,否則就喚醒,同理,生産者發現店員商品已滿就等待生産,否則就喚醒生産,虛假喚醒就是一些obj.wait()會在除了obj.notify()和obj.notifyAll()的其他情況被喚醒,而此時是不應該喚醒的。以下是一種解決辦法:
public class TestProductorAndCosumer {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Customer customer = new Customer(clerk);
new Thread(productor,"生産者 A").start();
new Thread(customer,"消費者 B").start();
new Thread(productor,"生産者 C").start();
new Thread(customer,"消費者 D").start();
}
}
//店員
class Clerk{
private int product = 0;
//進貨
public synchronized void get(){
while(product >= 1){// 為了避免虛假喚醒的問題,應該使用在循環中
System.out.println("産品已滿!!");
try {
this.wait();//産品已滿,等待消費者的通知
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" : "+ ++product);
this.notifyAll();
}
//賣貨
public synchronized void sale(){
while(product <= 0){
System.out.println("缺貨!!");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" : "+ --product);
this.notifyAll();
}
}
//生産者
class Productor implements Runnable{
private Clerk clerk;
public Productor(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.get();//20個員工不斷生産商品給店員
}
}
}
//消費者
class Customer implements Runnable{
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}
結果如下:
缺貨!!
缺貨!!
生産者 A : 1
消費者 D : 0
缺貨!!
缺貨!!
生産者 C : 1
消費者 B : 0
缺貨!!
缺貨!!
生産者 A : 1
消費者 D : 0
缺貨!!
缺貨!!
生産者 C : 1
消費者 B : 0
缺貨!!
缺貨!!
生産者 A : 1
消費者 D : 0
缺貨!!
生産者 C : 1
消費者 B : 0
解決辦法之二:使用Lock鎖
public class TestProductorAndCosumerforLock {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Customer customer = new Customer(clerk);
new Thread(productor,"生産者 A").start();
new Thread(customer,"消費者 B").start();
new Thread(productor,"生産者 C").start();
new Thread(customer,"消費者 D").start();
}
}
//店員
class Clerk{
private int product = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//進貨
public void get(){
lock.lock();
try {
while(product >= 1){// 為了避免虛假喚醒的問題,應該使用在循環中
System.out.println("産品已滿!!");
try {
condition.await();//産品已滿,等待消費者的通知
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" : "+ ++product);
condition.signalAll();
}finally{
lock.unlock();
}
}
//賣貨
public void sale(){
lock.lock();
try {
while(product <= 0){
System.out.println("缺貨!!");
try {
condition.await();;
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName()+" : "+ --product);
condition.signalAll();
}finally{
lock.unlock();
}
}
}
//生産者
class Productor implements Runnable{
private Clerk clerk;
public Productor(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.get();//20個員工不斷生産商品給店員
}
}
}
//消費者
class Customer implements Runnable{
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
clerk.sale();
}
}
}
注意上述代碼中改動的地方有很多,使用了接下來要說的Condition控制線程通信
8.Condition控制線程通信
在上述代碼中也使用了Condition控制線程通信,Condition接口描述了可能會與鎖有關聯的條件變量,在Condition對象中與wait、notify、notifyAll方法分别對應的是await、signal、signalAll。
一個面試題
編寫一個程式,開啟三個線程,這三個線程的ID分别為A、B、C,每一個線程将自己的ID列印10遍,輸出結果為
ABBCCCABBCCC….依次遞歸
public class TestABC {
public static void main(String[] args) {
final AlternateDemo ad = new AlternateDemo();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
ad.loopA(i);
}
}
},"A").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
ad.loopB(i);
}
}
},"B").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
ad.loopC(i);
System.out.println("================一輪結束==================");
}
}
},"C").start();
}
}
class AlternateDemo{
private int number = 1;// 目前正在執行線程的标記
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void loopA(int totalLoop){
lock.lock();
try {
if(number != 1){
condition1.await();
}
//列印
for(int i = 1; i <= 1; i++){
System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
}
//喚醒别人
number = 2;
condition2.signal();//隻喚醒線程B
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void loopB(int totalLoop){
lock.lock();
try {
if(number != 2){
condition2.await();
}
//列印
for(int i = 1; i <= 2; i++){
System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
}
//喚醒别人
number = 3;
condition3.signal();//隻喚醒線程C
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void loopC(int totalLoop){
lock.lock();
try {
if(number != 3){
condition3.await();
}
//列印
for(int i = 1; i <= 3; i++){
System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
}
//喚醒别人
number = 1;
condition1.signal();//隻喚醒線程A
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}