遇到过一个面试题,按顺序打印abc,输出十次,先说下解题思路,当打印a后,打印a和打印c的程序不能执行,只有打印b的程序可以执行,以此类推,就可以轻松解答了。
【Java|java线程,顺序打印abc】runnable实现如下:
class SortRunnable implements Runnable{private String value;
private final Object prev;
private final Object self;
SortRunnable(String value, Object prev, Object self) {
this.value = https://www.it610.com/article/value;
this.prev = prev;
this.self = self;
}@Override
public void run() {
int count = 10;
while (count> 0) {
synchronized (prev) {
synchronized (self) {
System.out.print(value);
count--;
self.notify();
}
try {
// 如果这里不设置超时时间,程序将进入死锁,不会停止
prev.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
调用方法:
public class Main {
public static void main(String[] args) {
String a = "a";
String b = "b";
String c = "c";
SortRunnable a1 = new SortRunnable("A", c, a);
SortRunnable b1 = new SortRunnable("B", a, b);
SortRunnable c1 = new SortRunnable("C", b, c);
new Thread(a1).start();
new Thread(b1).start();
new Thread(c1).start();
}
}
输出结果:
ABCABCABCABCABCABCABCABCABCABC
这里备一个planB:
public class Main {private static Boolean isThreadA = true;
private static Boolean isThreadB = false;
private static Boolean isThreadC = false;
public static void main(String[] args) {
final Main obj = new Main();
new Thread(() -> {
for (int i = 0;
i < 10;
i++) {
synchronized (obj) {
while(!isThreadA) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("A");
isThreadA = false;
isThreadB = true;
isThreadC = false;
obj.notifyAll();
}
}
}).start();
new Thread(() -> {
for (int i = 0;
i < 10;
i++) {
synchronized (obj) {
while(!isThreadB) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("B");
isThreadA = false;
isThreadB = false;
isThreadC = true;
obj.notifyAll();
}
}
}).start();
new Thread(() -> {
for (int i = 0;
i < 10;
i++) {
synchronized (obj) {
while(!isThreadC) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("C");
isThreadA = true;
isThreadB = false;
isThreadC = false;
obj.notifyAll();
}
}
}).start();
}
}
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)