线程中买家卖家解决死锁问题
普通线程买家与卖家之间的交互
public class Buyer implements Runnable{ private Phone phone; public Buyer(Phone phone) { super(); this.phone = phone; } @Override public void run() { for (int i = 0; i < 20; i++) { phone.buyer(); } } }
public class Salary implements Runnable{ private Phone phone; public Salary(Phone phone) { super(); this.phone = phone; } @Override public void run() { for (int i = 0; i < 20; i++) { if(i%2==0){ phone.salary("品牌的手机"); }else { phone.salary("杂牌子的手机"); } } } }
public class Phone { private String phoneName; public void salary(String phoneName){ System.out.println("商家拿出: "+phoneName); this.phoneName=phoneName; } public void buyer() { System.out.println("买家拿出:"+ this.phoneName +" 的钱"); } }
public class Main { public static void main(String[] args) { Phone phone=new Phone(); Buyer buyer=new Buyer(phone); Salary salary=new Salary(phone); Thread threadBuyer=new Thread(buyer); Thread threadSalary=new Thread(salary); threadBuyer.start(); threadSalary.start(); } }
使用同步锁和信号灯
public class Phone { private String phoneName; boolean bool = true;//信号灯 bool public synchronized void salary(String phoneName) { if (!bool) { //先进来不执行,让商家先拿出手机 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("商家拿出: " + phoneName); this.phoneName = phoneName; bool = false;//赋值false,表示当前商家已经拿出手机,唤醒买家 this.notify();//将当前对象唤醒 } public synchronized void buyer() { if (bool) { //当商家还没拿出手机先进入等待,睡眠 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("买家拿出:" + this.phoneName + "的钱"); bool=true;//赋值true,表示当前买家已经拿出钱,唤醒卖家 this.notify(); } }
上一篇:
通过多线程提高代码的执行效率例子