启动多个线程并按顺序执行

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 "";
    }
}

你可能感兴趣的:(java多线程)