本文共 1756 字,大约阅读时间需要 5 分钟。
public class NewThreadTest { public static void main(String[] args){ Q1 q1 = new Q1(); new Thread(new Producter1(q1)).start(); new Thread(new Consumer1(q1)).start(); }}class Q1{ private String name = "Merry"; private String sex = "girl"; boolean bFull = false ; //synchronized线程锁保证线程原子操作安全 //和lock与unlock效果相同 public synchronized void put(String name,String sex){ if (bFull==true){ try { //告诉当前线程放弃监视器并进入休眠状态,等待其他线程进入该监视器notify()唤醒 wait(); }catch (Exception e){ e.printStackTrace(); } } this.name = name ; try{ Thread.sleep(1000); }catch (Exception e){ e.printStackTrace(); }finally { this.sex = sex; bFull = true ; notify(); } } public synchronized void get(){ if (bFull==false){ try { wait(); }catch (Exception e){ e.printStackTrace(); } } System.out.println(this.name+"-->>"+this.sex); bFull = false; //唤醒监视器的第一个线程 //notifyAll()唤醒监视器所有wait线程,优先级高的先被唤醒 notify(); }}class Producter1 implements Runnable{ Q1 q1 = null; public Producter1(Q1 q1){ this.q1 = q1 ; } @Override public void run() { int i=0; while (true){ if (i==0){ q1.put("BOB","boy"); }else {q1.put("Merry","girl"); } i = (i+1)%2; } }}class Consumer1 implements Runnable{ private Q1 q1 = null ; public Consumer1(Q1 q1){ this.q1=q1 ; } @Override public void run() { while (true){ q1.get(); } }}
转载地址:http://kqnvb.baihongyu.com/