线程交替打印
发布人:shili8
发布时间:2025-03-04 11:03
阅读次数:0
**线程交替打印**
在多线程编程中,经常需要实现线程之间的协调工作。例如,在一个游戏程序中,我们可能需要让两个玩家交替进行操作。在这种情况下,我们可以使用线程来实现交替打印功能。
###1. 使用synchronized关键字最简单的方法是使用Java中的`synchronized`关键字来实现线程之间的互斥。我们可以在一个类中定义一个静态变量,用于标记当前哪个线程正在执行。
javapublic class ThreadAlternatingPrint {
private static int currentThread =0;
public static void main(String[] args) throws InterruptedException {
// 创建两个线程 Thread thread1 = new Thread(() -> print("线程1"));
Thread thread2 = new Thread(() -> print("线程2"));
// 启动线程 thread1.start();
thread2.start();
// 等待线程结束 thread1.join();
thread2.join();
}
private static synchronized void print(String message) {
while (currentThread ==0) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(message);
currentThread =1 - currentThread;
notifyAll();
}
}
在这个例子中,我们定义了一个静态变量`currentThread`来标记当前哪个线程正在执行。每个线程都有自己的打印函数,使用`synchronized`关键字来确保只有一个线程可以执行打印操作。
###2. 使用Lock对象另一种方法是使用Java中的`Lock`对象来实现线程之间的互斥。我们可以创建一个`ReentrantLock`对象,并在每个线程中使用它来获取锁。
javaimport java.util.concurrent.locks.ReentrantLock;
public class ThreadAlternatingPrint {
private static ReentrantLock lock = new ReentrantLock();
private static int currentThread =0;
public static void main(String[] args) throws InterruptedException {
// 创建两个线程 Thread thread1 = new Thread(() -> print("线程1"));
Thread thread2 = new Thread(() -> print("线程2"));
// 启动线程 thread1.start();
thread2.start();
// 等待线程结束 thread1.join();
thread2.join();
}
private static void print(String message) {
lock.lock();
try {
while (currentThread ==0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(message);
currentThread =1 - currentThread;
} finally {
lock.unlock();
}
}
}
在这个例子中,我们使用`ReentrantLock`对象来获取锁,并在每个线程中使用它来执行打印操作。
###3. 使用AtomicInteger最后一种方法是使用Java中的`AtomicInteger`类来实现线程之间的互斥。我们可以创建一个`AtomicInteger`对象,并在每个线程中使用它来获取当前值。
javaimport java.util.concurrent.atomic.AtomicInteger;
public class ThreadAlternatingPrint {
private static AtomicInteger currentThread = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
// 创建两个线程 Thread thread1 = new Thread(() -> print("线程1"));
Thread thread2 = new Thread(() -> print("线程2"));
// 启动线程 thread1.start();
thread2.start();
// 等待线程结束 thread1.join();
thread2.join();
}
private static void print(String message) {
int value = currentThread.get();
while (value ==0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(message);
currentThread.set(1 - value);
}
}
在这个例子中,我们使用`AtomicInteger`对象来获取当前值,并在每个线程中使用它来执行打印操作。
以上就是关于线程交替打印的三个方法。每种方法都有其优缺点,选择哪种方法取决于具体需求和场景。

