传统线程同步通信技术
/** * TraditionalThreadCommunication.java * cn.com.songjy * * Function: TODO* * ver date author * ────────────────────────────────── * 2012-7-24 songjianyong * * Copyright (c) 2012, TNT All Rights Reserved.*/package cn.com.songjy;/** * ClassName:TraditionalThreadCommunication * *子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程又循环100次,如此循环50次,请写出程序 * @author songjianyong * @version1.0 * @since v1.0 * @Date 2012-7-24 上午11:24:39*/public class TraditionalThreadCommunication {/** ** @method main * @param args * @throws* @since v1.0 */public static void main(String[] args) {final Businese businese = new Businese();new Thread(new Runnable() {public void run() {for(int j=0; j<50; j++){businese.sub(j);}}}).start();for(int j=0; j<50; j++){businese.main(j);}}}/*synchronized(锁)一般是放在需要访问的资源上的*/class Businese{private boolean sub = true;public synchronized void sub(int j){while(!sub){//这里用while不用if是因为有可能出现假唤醒的情况try {this.wait();} catch (InterruptedException e) {}}for (int i = 0; i < 10; i++) {System.out.println("sup thread sequence of" + i+ "loop of " + j);}sub = false;this.notify();}public synchronized void main( int j){while(sub){//这里用while不用if是因为有可能出现假唤醒的情况try {this.wait();} catch (InterruptedException e) {}}for (int i = 0; i < 100; i++) {System.out.println("main thread sequence of" + i+ "loop of " + j);}sub = true;this.notify();}}引自:http://down.51cto.com/data/443411
页:
[1]