传统线程同步通信技术

package cn.com.songjy.test.socket.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * ClassName:TraditionalThreadCommunication
 * 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程又循环100次,如此循环50次
 * 
 * @author songjy
 * @version 1.0
 * @since v1.0
 * @Date 2013-8-16 下午2:22:53
 */
public class TraditionalThreadCommunication {

	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 static Log log = LogFactory.getLog(Businese.class);
	private boolean sub = true;

	public synchronized void sub(int j) {
		/* 这里用while不用if是因为有可能出现假唤醒的情况 */
		while (!sub) {// 还没有轮到我(sub),继续等待(睡觉)
			try {
				wait();
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}
		}
		for (int i = 0; i < 10; i++) {
			log.info("sup thread sequence of" + i + "loop of " + j);
		}

		sub = false;// 执行完毕,变更状态
		notify();// 本次执行完毕,唤醒其他线程(main)
	}

	public synchronized void main(int j) {
		/* 这里用while不用if是因为有可能出现假唤醒的情况 */
		while (sub) {// 还没有轮到我(main),继续等待(睡觉)
			try {
				wait();
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}
		}
		for (int i = 0; i < 100; i++) {
			log.info("main thread sequence of" + i + "loop of " + j);
		}
		sub = true;// 执行完毕,变更状态
		notify();// 本次执行完毕,唤醒其他线程(sub)
	}
}


备注:wait()、notify()和notifyAll()都是Object类中的final方法,被所有的类继承、且不允许重写的方法

引自: http://down.51cto.com/data/443411

你可能感兴趣的:(synchronized,wait,notify,线程通信,互斥)