线程练习题2

一个线程打印 1~52,另一个线程打印字母A-Z。打印顺序为12A34B56C……5152Z。


package com.thread.second;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSecond {
	private static int count=0;
	
	private static Lock lock = new ReentrantLock();
	private static Condition condition;

	public static void main(String[] args) {
		condition = lock.newCondition();
		
		ExecutorService executor = Executors.newCachedThreadPool();
		executor.execute(new PrintNum());
		executor.execute(new PrintAB());
		executor.shutdown();
	}
	static class PrintNum implements Runnable{
		int num=1;
		public void run() {
			while(num<=52){
				lock.lock();
				try{
					while(count%3==0){
						condition.await();
					}
					System.out.print(" "+num+" ");
					count++;
					num++;
					condition.signalAll();
				}catch (InterruptedException e) {
					e.printStackTrace();
				}finally{
					lock.unlock();
				}
			}
		}
	}
	static class PrintAB implements Runnable{
		char ch='A';
		public void run() {
			while(ch<='Z'){
				lock.lock();
				try{
					while(count%3!=0){
						condition.await();
					}
					System.out.print(ch);
					count++;
					ch=(char)(ch+1);
					condition.signalAll();
				}catch (InterruptedException e) {
					e.printStackTrace();
				}finally{
					lock.unlock();
				}
			}
		}
	}

}


结果


A 1  2 B 3  4 C 5  6 D 7  8 E 9  10 F 11  12 G 13  14 H 15  16 I 17  18 J 19  20 K 21  22 L 23  24 M 25  26 N 27  28 O 29  30 P 31  32 Q 33  34 R 35  36 S 37  38 T 39  40 U 41  42 V 43  44 W 45  46 X 47  48 Y 49  50 Z 51  52 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值