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();
    }
}

你可能感兴趣的:(练习)