java实现线程交替打印1-52和A-Z

题目:

1.开启两个线程,一个线程打印A~Z,两一个线程打印1~52的数据。

2.实现交替打印,输出结果为12A34B...........5152Z.

3.请用多线程方式实现。

实现思路:通过锁(synchronized) 与wait(),notifyAll()的 或者lock、await()、signal()来实现,废话不多说,直接上代码:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* @author admin
* @create 2019-12-27-15:08
*/
public class Print {
public boolean letterFlag = true;//线程结束标记;
public boolean numFlag = true;
//数字的初始值
int num = 1;
//这里A~Z的字母对应的阿拉伯数字为65~90,
int letter = 65;
//线程等待标记
boolean flag = true;
Lock lock = new ReentrantLock();
Condition condLetter = lock.newCondition();
Condition condNum = lock.newCondition(); public void printLetter() {
if(letter>90){
letterFlag =false;
return;
}
lock.lock();
try { if (flag){
condLetter.await();
}
System.out.print((char)letter);
letter++;
flag=true;
condNum.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} public void printNum() {
if(num>=52){
numFlag =false;
return;
}
lock.lock();
try { if (!flag){
condNum.await();
}
System.out.print(num);
num++;
System.out.print(num);
num++;
flag=false;
condLetter.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Print print =new Print();
new Thread(new Runnable() {
@Override
public void run() {
while (print.numFlag){
print.printNum();
}
}
}).start(); new Thread(new Runnable() {
@Override
public void run() {
while (print.letterFlag){
print.printLetter();
}
}
}).start();
} }

运行结果为:

12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z
上一篇:javascript 判断浏览器的ie版本,替换html标签


下一篇:linux分区-df