多线程交替打印1~100的数字

第一次面试遇到的题,绷不住,不会写多线程

#include <iostream>
#include <thread>
using namespace std;
int num=0,r=100;
std::mutex mtx;
std::condition_variable cv;
void print(int flag)
{
     while(num<=r){
        unique_lock<mutex> lck(mtx);
        while(flag==(num&1)) cv.wait(lck);
        if(num<=r) cout <<num<< endl;
        num++;
        cv.notify_all();
    }

}
int main()
{
    thread t1(print,1);
    thread t2(print,0);
    t1.join();
    t2.join();
    return 0;
}

### Java多线程交替打印数字1100 以下是基于多种方法实现Java多线程交替打印数字1100的解决方案: #### 方法一:使用信号量(Semaphore) 此方法利用`java.util.concurrent.Semaphore`来协调多个线程的执行顺序。以下是一个完整的代码示例,其中三个线程按顺序打印数字。 ```java import java.util.concurrent.Semaphore; public class PrintNumbersWithSemaphores { private static final Semaphore first = new Semaphore(1); private static final Semaphore second = new Semaphore(0); private static final Semaphore third = new Semaphore(0); public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { try { for (int i = 1; i <= 100; i += 3) { first.acquire(); System.out.println(Thread.currentThread().getName() + ": " + i); second.release(); // 让第二个线程运行 } } catch (InterruptedException e) { e.printStackTrace(); } }, "Thread-1"); Thread t2 = new Thread(() -> { try { for (int i = 2; i <= 100; i += 3) { second.acquire(); System.out.println(Thread.currentThread().getName() + ": " + i); third.release(); // 让第三个线程运行 } } catch (InterruptedException e) { e.printStackTrace(); } }, "Thread-2"); Thread t3 = new Thread(() -> { try { for (int i = 3; i <= 100; i += 3) { third.acquire(); System.out.println(Thread.currentThread().getName() + ": " + i); first.release(); // 让第一个线程重新获取权限 } } catch (InterruptedException e) { e.printStackTrace(); } }, "Thread-3"); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); } } ``` 上述代码展示了如何通过信号量控制线程间的协作[^1]。 --- #### 方法二:使用ReentrantLock和Condition 该方法采用`java.util.concurrent.locks.ReentrantLock`以及`Condition`对象来同步线程操作。这种方式更加灵活且易于扩展。 ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PrintNumbersWithConditions { private static int number = 1; private static Lock lock = new ReentrantLock(); private static Condition condition1 = lock.newCondition(); private static Condition condition2 = lock.newCondition(); private static Condition condition3 = lock.newCondition(); public static void main(String[] args) { Thread t1 = new Thread(() -> { while (number <= 100) { lock.lock(); try { if (number % 3 != 1) { condition1.await(); } if (number <= 100) { System.out.println(Thread.currentThread().getName() + ": " + number++); } condition2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }, "Thread-1"); Thread t2 = new Thread(() -> { while (number <= 100) { lock.lock(); try { if (number % 3 != 2) { condition2.await(); } if (number <= 100) { System.out.println(Thread.currentThread().getName() + ": " + number++); } condition3.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }, "Thread-2"); Thread t3 = new Thread(() -> { while (number <= 100) { lock.lock(); try { if (number % 3 != 0 || number > 100) { condition3.await(); } if (number <= 100) { System.out.println(Thread.currentThread().getName() + ": " + number++); } condition1.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }, "Thread-3"); t1.start(); t2.start(); t3.start(); } } ``` 这段代码实现了更复杂的条件判断逻辑,并通过锁机制确保线程间的安全切换[^4]。 --- #### 方法三:使用volatile关键字与自旋等待 如果不想引入额外库,则可以借助`volatile`修饰符配合简单的轮询机制完成任务。不过需要注意的是,这种方案效率较低,在高并发场景下不推荐使用。 ```java class SharedResource { volatile int currentNumber = 1; } public class PrintNumbersWithVolatile { public static void main(String[] args) { SharedResource resource = new SharedResource(); Runnable taskA = () -> { while (resource.currentNumber <= 100) { synchronized (PrintNumbersWithVolatile.class) { if ((resource.currentNumber - 1) % 3 == 0 && resource.currentNumber <= 100) { System.out.println("Task A prints: " + resource.currentNumber++); } } try { Thread.sleep(1); } catch (InterruptedException ignored) {} } }; Runnable taskB = () -> { while (resource.currentNumber <= 100) { synchronized (PrintNumbersWithVolatile.class) { if ((resource.currentNumber - 2) % 3 == 0 && resource.currentNumber <= 100) { System.out.println("Task B prints: " + resource.currentNumber++); } } try { Thread.sleep(1); } catch (InterruptedException ignored) {} } }; Runnable taskC = () -> { while (resource.currentNumber <= 100) { synchronized (PrintNumbersWithVolatile.class) { if (resource.currentNumber % 3 == 0 && resource.currentNumber <= 100) { System.out.println("Task C prints: " + resource.currentNumber++); } } try { Thread.sleep(1); } catch (InterruptedException ignored) {} } }; new Thread(taskA).start(); new Thread(taskB).start(); new Thread(taskC).start(); } } ``` 这里采用了最基础的方式模拟了类似的流程[^3]。 --- #### 总结 以上三种方法各有优劣,具体选择取决于实际需求和技术背景。对于生产环境下的应用开发而言,建议优先考虑第二种方式即基于`ReentrantLock`加`Condition`的设计模式,因为它既兼顾了可读性和维护成本又具备较高的性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值