两个线程交替执行,一个打印1-52;一个打印A-Z;打印顺序为12A34B56C.....5152Z

package mutiThread;

public class alternatelyExecute {

	private static Object LOCK = new Object();
	private static boolean flag = false;

	static Thread thread01 = new Thread() {
		int num01 = 1;
		int num02 = 2;

		public void run() {
			synchronized (LOCK) {
				for (int i = 1; i <= 26; i++) {
					System.out.print(num01);
					System.out.print(num02);
					num01 += 2;
					num02 += 2;
					if (!flag) {
						flag = true;
						LOCK.notify();
						if (i < 26) {
							try {
								LOCK.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	};

	static Thread thread02 = new Thread() {
		int c = 65;

		public void run() {
			synchronized (LOCK) {
				for (int i = 1; i <= 26; i++) {
					System.out.print((char) c++);
					System.out.print(" ");
					if (flag) {
						flag = false;
						LOCK.notify();
						if (i < 26) {
							try {
								LOCK.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	};

	public static void main(String[] args) {
		thread01.start();
		thread02.start();
	}
}

12A 34B 56C 78D 910E 1112F 1314G 1516H 1718I 1920J 2122K 2324L 2526M 2728N 2930O 3132P 3334Q 3536R 3738S 3940T 4142U 4344V 4546W 4748X 4950Y 5152Z 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值