JAVA多线程--实现生产者/消费者模型:一对一

要实现的功能:线程A将一个数据放入队列,然后通知B进行处理,B处理完后再通知A放一个数据入队列。

package javathreadlearn;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


public class ReentrantLockTest {
    public static ReentrantLock lock = new ReentrantLock();
    public static Condition condition = lock.newCondition();
    public static LinkedList<String> queue = new LinkedList<>();
    public static boolean hasCompleted = false;
    public static void main(String[] args){
        ThreadA a = new ThreadA();
        ThreadB b = new ThreadB();
        b.setName("thread-B");
        a.start();
        b.start();
        try {
            a.join();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
class ThreadA extends Thread{
    @Override
    public void run(){
        for (int i = 0;i<10;i++) {
            try{
                ReentrantLockTest.lock.lock();
                while (ReentrantLockTest.hasCompleted == true){
                    ReentrantLockTest.condition.await();
                }
                ReentrantLockTest.queue.add(String.valueOf(i));
                ReentrantLockTest.hasCompleted = true;
                ReentrantLockTest.condition.signal();
            } catch (InterruptedException e){
                e.printStackTrace();
            }finally
            {
                ReentrantLockTest.lock.unlock();
            }
        }
    }

}
class ThreadB extends Thread{
    @Override
    public void run(){
        while (true) {
            try{
                ReentrantLockTest.lock.lock();
                while (ReentrantLockTest.hasCompleted == false){
                    ReentrantLockTest.condition.await();
                }
                System.out.println(ReentrantLockTest.queue.remove());
                ReentrantLockTest.hasCompleted = false;
                ReentrantLockTest.condition.signal();
            } catch (InterruptedException e){
                e.printStackTrace();         
            }finally
            {
                ReentrantLockTest.lock.unlock();
            }
            
        }
    }
}

 代码运行结果如下所示:

0
1
2
3
4
5
6
7
8
9
A-exit

可以看到,A结束了,但是B还是在执行。如何解决呢?

可以用 interrupt来打标记。然后在B线程中检测标记,如果结束就退出循环。

猜你喜欢

转载自blog.csdn.net/shuzishij/article/details/86106880