(黑马Java多线程与并发库高级应用)04 传统线程同步通信技术
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(黑马Java多线程与并发库高级应用)04 传统线程同步通信技术相关的知识,希望对你有一定的参考价值。
子线程10次,然后主线程100次,然后子线程10次,然后主线程100次。循环50次
package cn.itcast.heima2; public class TraditionalThreadComunication { public static void main(String[] args) { // TODO Auto-generated method stub Business business = new TraditionalThreadComunication().new Business(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 50; i++) { business.sub(i); } } }).start(); for (int i = 0; i < 50; i++) { business.main(i); } } class Business { private boolean bShouldSub=true; public synchronized void sub(int i) { if(!bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int j = 0; j < 10; j++) { System.out.println("sub thread sequence:" + j + " loop of " + i); } bShouldSub=false; this.notify(); } public synchronized void main(int i) { if(bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int j = 0; j < 100; j++) { System.out.println("main thread sequence:" + j + " loop of " + i); } bShouldSub=true; this.notify(); } } }
以上是关于(黑马Java多线程与并发库高级应用)04 传统线程同步通信技术的主要内容,如果未能解决你的问题,请参考以下文章
(黑马Java多线程与并发库高级应用)02 传统定时器技术回顾