java怎么实现两个线程交替打印

45次阅读
没有评论

共计 1252 个字符,预计需要花费 4 分钟才能阅读完成。

可以使用 synchronized 关键字和 wait()、notify() 方法来实现两个线程交替打印。

下面是一个简单的例子,其中 A 线程打印奇数,B 线程打印偶数。

public class AlternatePrint {private int count = 1;
    private final Object lock = new Object();

    public static void main(String[] args) {AlternatePrint alternatePrint = new AlternatePrint();
        Thread threadA = new Thread(() -> alternatePrint.printOdd());
        Thread threadB = new Thread(() -> alternatePrint.printEven());
        threadA.start();
        threadB.start();}

    public void printOdd() {while (count <= 100) {synchronized (lock) {if (count % 2 != 0) {System.out.println(Thread.currentThread().getName() + ": " + count);
                    count++;
                    lock.notify(); // 唤醒等待的线程 
                } else {try {lock.wait(); // 当前线程等待 
                    } catch (InterruptedException e) {e.printStackTrace();
                    }
                }
            }
        }
    }

    public void printEven() {while (count <= 100) {synchronized (lock) {if (count % 2 == 0) {System.out.println(Thread.currentThread().getName() + ": " + count);
                    count++;
                    lock.notify(); // 唤醒等待的线程 
                } else {try {lock.wait(); // 当前线程等待 
                    } catch (InterruptedException e) {e.printStackTrace();
                    }
                }
            }
        }
    }
}

在上面的例子中,使用一个共享的 lock 对象作为锁,每个线程通过 synchronized(lock) 来获取锁对象。当 count 为奇数时,A 线程打印并增加 count,然后调用 lock.notify() 方法唤醒正在等待的 B 线程。当 count 为偶数时,B 线程打印并增加 count,然后调用 lock.notify() 方法唤醒正在等待的 A 线程。如果 count 的值不符合当前线程的打印条件时,当前线程调用 lock.wait() 方法进入等待状态,直到被唤醒。

需要注意的是,lock.wait() 和 lock.notify() 方法只能在 synchronized 块中调用,否则会抛出 IllegalMonitorStateException 异常。同时,线程的启动顺序不确定,所以 A 和 B 线程的打印顺序可能会有不同。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1252字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)