Java 4个线程交替打印0到400

Java 4个线程交替打印0到400

package learn_thread;

public class Demo6 {
    private static final int ThreadNum = 4;

    public static void main(String[] args) {
        CyclePrint cyclePrint = new CyclePrint();
        for (int i = 0; i < ThreadNum; i++) {
            final int curFlag = i;
            final int nextFlag = (curFlag + 1) % ThreadNum;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cyclePrint.print(curFlag, nextFlag, curFlag, ThreadNum);
                }
            }, "T" + curFlag).start();
        }
    }

}

class CyclePrint {
    private static int flag = 0;
    private static final int maxValue = 400;

    public void print(int curFlag, int nextFlag, int start, int threadNum) {
        for (int i = start; i <= maxValue; i += threadNum) {
            synchronized (this) {
                while (curFlag != flag) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                    }
                }
                System.out.println(Thread.currentThread().getName() + "-" + i);
                flag = nextFlag;
                notifyAll();
            }
        }
    }
}

### Java 中实现两个线程交替打印的方法 以下是几种常见的方法用于实现两个线程之间的交替打印功能: #### 方法一:使用 `synchronized` 和 `wait/notify` 这种方法利用对象锁机制,通过调用 `wait()` 让当前线程等待,并释放锁;当其他线程完成工作后,调用 `notify()` 唤醒等待中的线程。 ```java public class AlternatePrinting { private static int count = 0; private final Object lock = new Object(); public static void main(String[] args) { AlternatePrinting ap = new AlternatePrinting(); Thread t1 = new Thread(ap::printEven, "Thread-A"); Thread t2 = new Thread(ap::printOdd, "Thread-B"); t1.start(); t2.start(); } private void printEven() { synchronized (lock) { while (count <= 10) { if (count % 2 != 0) { try { lock.wait(); // 当前线程进入等待状态 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notify(); // 唤醒另一个线程 } } } } private void printOdd() { synchronized (lock) { while (count <= 10) { if (count % 2 == 0) { try { lock.wait(); // 当前线程进入等待状态 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notify(); // 唤醒另一个线程 } } } } } ``` 此代码展示了如何通过 `wait()` 和 `notify()` 来控制线程间的交互[^2]。 --- #### 方法二:使用 `ReentrantLock` 和条件变量 相比传统的 `synchronized` 锁定方式,`ReentrantLock` 提供更灵活的锁定操作以及显式的条件支持。 ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class AlternatePrintWithLock { private Lock lock = new ReentrantLock(); private Condition conditionA = lock.newCondition(); private Condition conditionB = lock.newCondition(); private volatile boolean flag = true; // 控制哪个线程运行 public static void main(String[] args) { AlternatePrintWithLock app = new AlternatePrintWithLock(); Thread threadA = new Thread(app::taskA, "Thread-A"); Thread threadB = new Thread(app::taskB, "Thread-B"); threadA.start(); threadB.start(); } private void taskA() { lock.lock(); try { for (int i = 0; i < 5; i++) { while (!flag) { conditionA.await(); // 如果不是 A 的回合,则等待 } System.out.println(Thread.currentThread().getName() + ": " + i * 2); // 打印偶数 flag = false; conditionB.signal(); // 唤醒 B 线程 } } catch (Exception ex) { ex.printStackTrace(); } finally { lock.unlock(); } } private void taskB() { lock.lock(); try { for (int i = 0; i < 5; i++) { while (flag) { conditionB.await(); // 如果不是 B 的回合,则等待 } System.out.println(Thread.currentThread().getName() + ": " + (i * 2 + 1)); // 打印奇数 flag = true; conditionA.signal(); // 唤醒 A 线程 } } catch (Exception ex) { ex.printStackTrace(); } finally { lock.unlock(); } } } ``` 该示例说明了如何借助 `ReentrantLock` 及其关联的条件变量来协调多个线程的行为[^4]。 --- #### 方法三:使用信号量 (`Semaphore`) 信号量是一种计数器形式的同步工具,可用于管理资源访问权限或协调线程活动。 ```java import java.util.concurrent.Semaphore; public class AlternateUsingSemaphore { private Semaphore semaphoreA = new Semaphore(1); // 初始许可给 A private Semaphore semaphoreB = new Semaphore(0); public static void main(String[] args) throws InterruptedException { AlternateUsingSemaphore aus = new AlternateUsingSemaphore(); Thread threadA = new Thread(aus::taskA, "Thread-A"); Thread threadB = new Thread(aus::taskB, "Thread-B"); threadA.start(); threadB.start(); } private void taskA() { for (int i = 0; i < 5; i++) { try { semaphoreA.acquire(); // 获取许可 System.out.println(Thread.currentThread().getName() + ": " + i * 2); // 打印偶数 semaphoreB.release(); // 给 B 发放许可 } catch (InterruptedException e) { e.printStackTrace(); } } } private void taskB() { for (int i = 0; i < 5; i++) { try { semaphoreB.acquire(); // 获取许可 System.out.println(Thread.currentThread().getName() + ": " + (i * 2 + 1)); // 打印奇数 semaphoreA.release(); // 给 A 发放许可 } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 上述代码片段解释了如何运用 `Semaphore` 进行线程间通信和协作。 --- #### 总结 以上三种方法各有优劣,在实际开发过程中可以根据具体需求选择合适的技术手段。如果追求简单易懂,可以选择基于 `synchronized` 的方案;对于复杂场景或者需要更高灵活性时,推荐采用 `ReentrantLock` 或者 `Semaphore`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值