一个线程打印 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