2个线程顺序工作

2个线程,一个线程先写,然后另外一个线程读,以此循环。

static int i = 8;
static Object obj = new Object();
public static void main(String[] args) throws InterruptedException {
    Thread read = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {
                synchronized (obj) {
                    System.out.println("read:" + i);
                    
                    obj.notify();
                    
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                }
            }
        }
    });
    Thread write = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {
                synchronized (obj) {
                    i = j;
                    System.out.println("write:" + i);
                    
                    obj.notify();
                    
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
    write.setName("write");
    read.setName("read");
    
    write.start();
    Thread.sleep(10);
    read.start();
}

 

转载于:https://www.cnblogs.com/allenwas3/p/8644690.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
互斥锁可以用来协调多个线程工作顺序,实现同步操作。当多个线程需要访问共享资源时,使用互斥锁可以保证同一时刻只有一个线程可以访问共享资源,从而避免多个线程同时修改共享资源导致的数据不一致问题。 以下是使用互斥锁协调多个线程工作顺序的示例: 1. 定义一个互斥锁对象 ```c++ std::mutex mtx; ``` 2. 在需要访问共享资源的代码块前加锁 ```c++ mtx.lock(); // 访问共享资源的代码块 mtx.unlock(); ``` 3. 确保访问共享资源的代码块执行完毕后解锁 ```c++ mtx.lock(); // 访问共享资源的代码块 mtx.unlock(); ``` 4. 保证所有线程都按照指定的顺序执行 例如,假设有三个线程 A、B、C,需要按照 A -> B -> C 的顺序执行,可以使用如下代码: ```c++ #include <mutex> #include <thread> std::mutex mtx; void threadA() { mtx.lock(); // 线程 A 的代码 mtx.unlock(); } void threadB() { mtx.lock(); // 线程 B 的代码 mtx.unlock(); } void threadC() { mtx.lock(); // 线程 C 的代码 mtx.unlock(); } int main() { std::thread tA(threadA); std::thread tB(threadB); std::thread tC(threadC); tA.join(); tB.join(); tC.join(); return 0; } ``` 在该示例中,使用互斥锁 mtx 来保证线程 A、B、C 按照 A -> B -> C 的顺序执行。线程 A 在执行之前会先锁定互斥锁 mtx,执行完毕后再解锁,这样就保证了线程 B 和 C 在 A 执行完毕之前无法执行。同理,线程 B 和 C 也会在执行之前锁定互斥锁 mtx,执行完毕后再解锁,从而保证了线程执行的顺序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值