美文网首页
两个线程交替打印 0 - 99

两个线程交替打印 0 - 99

作者: leeehao | 来源:发表于2020-08-06 15:53 被阅读0次

    volatile 控制

    public class ThreadPrint {
    
        private static volatile int i = 0;
        private static volatile boolean who = true;
    
        public static void main(String[] args) {
            new Thread(() -> {
                while (true) {
                    if (who) {
                        // 出口
                        if (i == 100) {
                            who = !who;
                            break;
                        }
                        System.out.println("t1 = " + i);
                        i++;
                        who = !who;
                    }
                }
            }).start();
    
            new Thread(() -> {
                while (true) {
                    if (!who) {
                        if (i == 100) {
                            who = true;
                            break;
                        }
                        System.out.println("t2 - " + i);
                        i++;
                        who = !who;
                    }
                }
            }).start();
        }
    
    }
    

    notify 机制

    public class ThreadPrint {
    
        private static volatile int i = 0;
        private static Object lock = new Object();
    
        public static void main(String[] args) {
            new Thread(() -> {
                synchronized(lock) {
                    while (true) {
                        if (i == 100) break;
                        System.out.println("t1 - " + i);
                        i++;
                        lock.notify();
                        try {
                            // 释放锁
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 通知另一线程结束
                    lock.notify();
                }
            }).start();
    
            new Thread(() -> {
                synchronized (lock) {
                    while (true) {
                        if (i == 100) break;
                        System.out.println("t2 - " + i);
                        i++;
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 通知另一线程结束
                    lock.notify();
                }
            }).start();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:两个线程交替打印 0 - 99

          本文链接:https://www.haomeiwen.com/subject/sittdktx.html