Java基础 - Lock 的使用 三个线程交替打印 0-100

说明

最近碰到一个问题,使用三个线程交替打印 0-100 。主要考察多线程并发同步,锁的使用。这里记录下我用 Lock 和 多个 Condition 的实现方式。

在刚开始实现时,发现在数字输出完毕后,主线程无法停止,最后只能在判断满足条件后直接退出 JVM。这个原因是有线程在调用 await 方法后,没有被唤醒,导致线程没有正常结束。

所以,在每个线程执行完毕退出释放锁前,都要进行一次顺序唤醒操作。

还有一点需要注意的是,尽量不要在循环中使用 try catch 语句。

正文

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintNum {


    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition c1 = lock.newCondition();
        Condition c2 = lock.newCondition();
        Condition c3 = lock.newCondition();
        AtomicInteger count = new AtomicInteger(0);
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    while (true) {
                        if (count.get() > 100) {
                            return;
                        }
                        System.out.println(Thread.currentThread().getName() + "-" + count.getAndAdd(1));
                        c2.signal();

                        c1.await();
                    }
                } catch (Exception e) {
                } finally {
                    c2.signal();
                    lock.unlock();
                }

            }
        };

        Runnable task2 = new Runnable() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    while (true) {
                        if (count.get() > 100)
                            return;
                        System.out.println(Thread.currentThread().getName() + "-" + count.getAndAdd(1));
                        c3.signal();
                        c2.await();
                    }
                } catch (Exception e) {
                } finally {
                    c3.signal();
                    lock.unlock();
                }

            }
        };

        Runnable task3 = new Runnable() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    while (true) {
                        if (count.get() > 100)
                            return;
                        System.out.println(Thread.currentThread().getName() + "-" + count.getAndAdd(1));
                        c1.signal();
                        c3.await();
                    }
                } catch (Exception e) {
                } finally {
                    c1.signal();
                    lock.unlock();
                }

            }
        };
        Thread t1 = new Thread(task1, "A");
        t1.start();
        Thread t2 = new Thread(task2, "B");
        t2.start();
        Thread t3 = new Thread(task3, "C");
        t3.start();
        try {
            System.out.println("任务线程已启动");
            t1.join();
            t2.join();
            t3.join();
            System.out.println("线程执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要编写一个多线程程序,您需要遵循以下步骤: 1. 引入线程库:您需要引入适当的线程库,例如Java中的java.util.concurrent或C++中的pthread.h。 2. 创建线程:您需要创建线程,可以使用线程库中提供的函数来创建线程并指定线程函数。 3. 启动线程:一旦您创建了线程并指定了线程函数,您需要启动线程以开始执行线程函数。 4. 同步线程:如果您的线程需要互相同步,您需要使用锁或信号量等同步机制。 5. 终止线程:当线程完成其工作或您需要停止线程时,您需要终止线程。 下面是一个实现您描述的多线程程序的示例代码: Java代码: ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MultiThread { public static void main(String[] args) { Lock lock = new ReentrantLock(); Condition conditionA = lock.newCondition(); Condition conditionB = lock.newCondition(); Condition conditionC = lock.newCondition(); int count = 0; Thread threadA = new Thread(new Runnable() { @Override public void run() { while (count < 100) { lock.lock(); try { if (count % 10 != 0 || count == 0) { System.out.println("Thread A: " + count++); } else { conditionB.signal(); conditionA.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }); Thread threadB = new Thread(new Runnable() { @Override public void run() { while (count < 100) { lock.lock(); try { if (count % 10 != 0 || count == 0) { System.out.println("Thread B: " + count++); } else { conditionC.signal(); conditionB.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }); Thread threadC = new Thread(new Runnable() { @Override public void run() { while (count < 100) { lock.lock(); try { if (count % 10 == 0 && count != 0) { System.out.println("Thread C: " + count++); conditionA.signal(); conditionC.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }); threadA.start(); threadB.start(); threadC.start(); } } ``` 在这个例子中,我们使用Java中的ReentrantLockCondition实现线程同步。我们创建了三个线程:Thread A,Thread B和Thread C。Thread A和Thread B交替打印数字,当计数到10的倍数时,Thread C来打印。 Python代码: ```python import threading lock = threading.Lock() conditionA = threading.Condition(lock) conditionB = threading.Condition(lock) conditionC = threading.Condition(lock) count = 0 def thread_a(): global count while count < 100: with lock: if count % 10 != 0 or count == 0: print("Thread A:", count) count += 1 else: conditionB.notify() conditionA.wait() def thread_b(): global count while count < 100: with lock: if count % 10 != 0 or count == 0: print("Thread B:", count) count += 1 else: conditionC.notify() conditionB.wait() def thread_c(): global count while count < 100: with lock: if count % 10 == 0 and count != 0: print("Thread C:", count) count += 1 conditionA.notify() conditionC.wait() threadA = threading.Thread(target=thread_a) threadB = threading.Thread(target=thread_b) threadC = threading.Thread(target=thread_c) threadA.start() threadB.start() threadC.start() ``` 在这个例子中,我们使用了Python中的threading库来实现多线程。我们创建了三个线程:Thread A,Thread B和Thread C。Thread A和Thread B交替打印数字,当计数到10的倍数时,Thread C来打印。我们使用了锁和条件变量来实现线程同步。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值