爱自习的暴鲤龙:
有的时候能够结束退出,有的时候就是一直在Ob无限循环了。。。有兴趣帮帮忙看看的嘛。啥原因。。
public class TestThread { public static void main(String[] args) { Count aCount =new Count(100) ; Count bCount =new Count(100) ; final Count cCount =new Count(0) ; long l = System.currentTimeMillis(); Thread a= new Thread(new Runnable() { @Override public void run() { while (aCount.total > 0) { synchronized (cCount){ aCount.reduce(); try { cCount.add(); System.out.println(Thread.currentThread().getName()+"-"+aCount.trade+":t aCount:"+aCount.total+"t cCount:"+cCount.total); cCount.notify(); cCount.wait();//让处锁 } catch (InterruptedException e) { e.printStackTrace(); } cCount.notify(); } } } },"Thread A"); Thread b = new Thread(new Runnable() { @Override public void run() { while(bCount.total<200){ if (cCount.total>0){ synchronized (cCount){ try { cCount.reduce(); System.out.println(Thread.currentThread().getName()+"-"+bCount.trade+":t bCount:"+bCount.total+"t cCount:"+cCount.total); cCount.notify(); cCount.wait(); } catch (InterruptedException e) { e.printStackTrace(); } bCount.add(); cCount.notify(); } } } } },"Thread B"); Thread o = new Thread(()->{ while(bCount.total<200){ System.out.println("aCount.total:"+aCount.total+"t bCount.total:"+bCount.total+"t cCount.total:"+cCount.total); } },"Thread O:"); o.start(); a.start(); b.start(); } public static class Count implements AddAndReduce{ int total; int trade; public Count(int total){ this.total = total; this.trade= 0; } @Override public void add() { this.total +=1; this.trade +=1; } @Override public void reduce() { this.total -=1; this.trade +=1; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)