三线程联系输出abc

来源:互联网 发布:辐射4美女捏脸数据 编辑:程序博客网 时间:2024/06/08 02:42
public class ThreadPrint {    /**     * @author my_corner     * @param     * @return     * @throws InterruptedException     */    public static void main(String[] args) throws InterruptedException {        PrintTask task = new PrintTask();        Thread a = new Thread(task);        a.setName("a");        Thread b = new Thread(task);        b.setName("b");        Thread c = new Thread(task);        c.setName("c");        a.start();        b.start();        c.start();    }}class PrintTask implements Runnable {    private int times = 0;    /**         *          */    @Override    public void run() {        while (times < 300) {            synchronized (this) {                if (times % 3 == 0) {                    if ("a".equals(Thread.currentThread().getName())) {                        System.out.print("a");                        times++;                        this.notifyAll();                    } else {                        try {                            this.wait();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                }                if (times % 3 == 1) {                    if ("b".equals(Thread.currentThread().getName())) {                        System.out.print("b");                        times++;                        this.notifyAll();                    } else {                        try {                            this.wait();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                }                if (times % 3 == 2) {                    if ("c".equals(Thread.currentThread().getName())) {                        System.out.print("c");                        times++;                        this.notifyAll();                    } else {                        try {                            this.wait();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                }            }        }    }}


引用至:http://www.iteye.com/topic/1119297
0 0
原创粉丝点击