现在的位置: 首页 > 综合 > 正文

两个线程,一个线程输出1,一个线程输出2,循环输出

2018年05月12日 ⁄ 综合 ⁄ 共 708字 ⁄ 字号 评论关闭
/**
 * 两个线程,一个线程输出1,一个线程输出2,
 * 
 * @author ffr@cnic.cn
 * 
 */
public class SleepAndWaitThread2 {
	public static void main(String[] args) {
		OneThread one = new OneThread();
		TwoThread two = new TwoThread();
		one.start();
		two.start();
	}
}

class OneThread extends Thread {

	@Override
	public void run() {
		synchronized (SleepAndWaitThread2.class) {
			while (true) {
				System.out.println("1");
				try {
					SleepAndWaitThread2.class.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				SleepAndWaitThread2.class.notify();
			}
		}
	}
}

class TwoThread extends Thread {

	@Override
	public void run() {
		synchronized (SleepAndWaitThread2.class) {
			while (true) {
				System.out.println("2");
				SleepAndWaitThread2.class.notify();
				try {
					SleepAndWaitThread2.class.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

抱歉!评论已关闭.