Java 3个线程依次打印ABC,并且循环10次

/**
 * Java 3个线程依次打印ABC,并且循环10次
 * 
 * @author http://blog.csdn.net/qq2439169750
 */
public class ABCThread {
	public static void main(String[] args) {
		new Thread(new Printer("    A", 0)).start();
		new Thread(new Printer("  B", 1)).start();
		new Thread(new Printer("C", 2)).start();
	}
}

class Printer implements Runnable {
	private static int flag = 0;// 控制该哪个线程打印
	private String str;// 要打印的字符
	private int id;

	public Printer(String _str, int _id) {
		str = _str;
		id = _id;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			synchronized (Printer.class) {// 同一时刻只有一个Printer的实例执行

				while (flag % 3 != id) {
					try {
						Printer.class.wait();// 注意是Printer.class
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				System.out.println(str);
				flag++;
				/*
				 * Note that the call to notifyAll does not immediately activate
				 * a waiting thread. It only unblocks the waiting threads so
				 * that they can compete for entry into the object after the
				 * current thread has exited the synchronized method.
				 * ------《CoreJava》多线程
				 */
				// 即当前线程退出同步块之后,其他线程就会被唤醒
				Printer.class.notifyAll();
			}

		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值