当前位置:网站首页>多线程交替输出AB

多线程交替输出AB

2022-06-11 03:13:00 菜鸟小窝

方式一

public class T1 {
    
    public static void main(String[] args) {
    
        new T1().fun();
    }

    private void fun() {
    
        try {
    
            Object lock = new Object();
            Thread thread1 = new Thread(() -> {
    
                try {
    
                    synchronized (lock) {
    
                        for (int i = 0; i < 10; i++) {
    
                            System.out.println("A");
                            lock.notify();
                            lock.wait();
                        }
                    }
                } catch (Exception e) {
    
                    e.printStackTrace();
                }
            });

            Thread thread2 = new Thread(() -> {
    
                try {
    
                    synchronized (lock) {
    
                        for (int i = 0; i < 10; i++) {
    
                            lock.wait();
                            System.out.println("B");
                            lock.notify();
                        }
                    }
                } catch (Exception e) {
    
                    e.printStackTrace();
                }
            });

            thread2.start();
            Thread.sleep(100);
            thread1.start();
        } catch (Exception e) {
    
            e.printStackTrace();
        }
    }
}

方式二

package look.LookUse;

public class T2 {
    
    static Thread ta, tb;

    public static void main(String[] args) {
    
        int num = 10;
        Thread lock = Thread.currentThread();
        ta = new Thread(() -> {
    
            for (int i = 0; i < num; i++) {
    
                try {
    
                    while (tb.getState() != Thread.State.WAITING) {
    
                    }
                    synchronized (lock) {
    
                        System.out.println("A" + i);
                        lock.notify();
                        if (i != num - 1)
                            lock.wait();
                    }
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
            }
        });
        tb = new Thread(() -> {
    
            for (int i = 0; i < num; i++) {
    
                try {
    
                    synchronized (lock) {
    
                        lock.notify();
                        lock.wait();
                        System.out.println("B" + i);
                    }
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
            }
        });
        ta.start();
        tb.start();
    }
}

原网站

版权声明
本文为[菜鸟小窝]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_25775675/article/details/113179253