【Java多线程练习(三个线程顺序打印A,B,C)】回顾一下Java多线程,使用wait/notify 控制线程协调,三个线程顺序打印A,B,C 打印三次
package com.levin.lang;
public class Lock {
public static class PrintThread extends Thread {
private Object obj;
private volatile String str;
private int i = 0;
PrintThread(Object obj, String str) {
this.obj = obj;
this.str = str;
}@Override
public void run() {
synchronized (obj) {
while (i < 9) {
if (str.equals(currentThread().getName())) {
i++;
System.out.println(Thread.currentThread().getName());
switch (str) {
case "A":
str = "B";
break;
case "B":
str = "C";
break;
case "C":
str = "A";
break;
}
} else {
try {
obj.notifyAll();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}public static void main(String[] args) {
Object lock = new Object();
String str = "A";
PrintThread p1 = new PrintThread(lock, str);
Thread t1 = new Thread(p1);
Thread t2 = new Thread(p1);
Thread t3 = new Thread(p1);
t1.setName("A");
t2.setName("B");
t3.setName("C");
t1.start();
t2.start();
t3.start();
}
}
推荐阅读
- 练习|vue+element实现手机号验证码注册
- Python|python:while打印正三角形
- 牛客练习赛25 因数个数和
- Python|Python练习实例——星号三角形
- python输出棱形及对称三角
- 2.任何一个自然数m的立方均可写成m个连续奇数之和
- 2017年09月23日普级组 看电影
- 练习|如何对解压缩版的Tomcat进行启动