wait,notify,notifyAll作用、用法 wait()/wait(time)使线程进入阻塞阶段-线程状态进入WAITING/TIMED_WAITING状态,notify方法会随机唤醒其他状态是WAITING/TIMED_WAITING状态的线程,notifyAll会唤醒全部处于WAITING/TIMED_WAITING状态的线程。wait,notify,notifyAll方法只能用于synchronized修饰的代码块中。
代码块 【启动多个线程并按顺序执行】下面是我在面试中遇到的面试题,启动线程A/B/C,并一次循环打印线程名ABCABC…十次。
package multithreading.threadcoreknowledge.sixthreadstates;
/**
* @author csy
* @date 2020/5/12 20:09
*/
public class ThreeThreadPrint implements Runnable{
private Print p;
public ThreeThreadPrint(Print p){
this.p= print;
}@Override
public void run() {
try {
p.print();
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
Print name = new Print();
ThreeThreadPrint threadPrintA = new ThreeThreadPrint(name);
ThreeThreadPrint threadPrintB = new ThreeThreadPrint(name);
ThreeThreadPrint threadPrintC = new ThreeThreadPrint(name);
Thread threadA = new Thread(threadPrintA);
Thread threadB = new Thread(threadPrintB);
Thread threadC = new Thread(threadPrintC);
threadA.setName("A");
threadB.setName("B");
threadC.setName("C");
threadA.start();
threadB.start();
threadC.start();
}
}class Print{
//定义当前应打印线程名
private String m = "A";
/**
* 功能描述: 判断当前线程是否需要打印
* @param: [] 参数
* @return: void 返回值
* @date: 2020/5/12 22:17
*/
public synchronized void print() throws InterruptedException{
int i = 0;
while(i<10){
String name = Thread.currentThread().getName();
if(m.equals(name)){
//当前打印线程正好是当前应打印线程-进行打印
System.out.print(m);
m = changStr(m);
i++;
notifyAll();
if(i != 10){
wait();
}
}else{
notifyAll();
wait();
}
}
}
/**
* 功能描述: 修改当前应执行线程名
* @param: [yStr] 参数
* @return: java.lang.String 返回值
* @date: 2020/5/12 22:16
*/
public String changStr(String yStr){
switch (yStr){
case "A":
return "B";
case "B":
return "C";
case "C":
return "A";
}
return "";
}
}
推荐阅读
- 线程多对多交替打印-condition
- java|使用线程Thread和Runnable输出1到100之间的偶数
- java多线程轮流打印数据问题
- Java|面试必问!Java 多线程中两个线程交替执行,一个输出偶数,一个输出奇数
- 【Java多线程实战设计】用三个线程按顺序循环打印abc三个字母,比如abcabcabc
- java多线程(循环输出ABC)
- JAVA并发编程——Callable接口和FutureTask简介和使用
- 多线程(至少三个线程)分别打印A、B、C,要求按ABC的顺序循环打印10次。