JavaBasic:Concurrent-Condition

  • Condition可以替代wait/notify
    Condition.await/signal/sigalAll原理和wait/notify/notifyAll一致
    await()会释放当前锁,进入等待状态
    signal()会唤醒某个等待线程
    signalAll()会唤醒所有等待线程
    唤醒线程从await()返回后需要重新获得锁
  • Condition对象必须从ReentrantLock对象获取
  • ReentrantLock+Condition可以替代synchronized+wait/notify

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class TaskQueue{
    final Queue<String> queue=new LinkedList<>();

    final Lock lock=new ReentrantLock();
    final Condition notEmpty=lock.newCondition();

    public String getTask() throws Exception{
        lock.lock();
        try{
            while(this.queue.isEmpty()){
                //当queue为空的时候,调用await()方法,让线程进入等待状态
                notEmpty.await();
            }
            return queue.remove();

        }finally {
            lock.unlock();
        }
    }

    public void addTask(String name) throws Exception{
        lock.lock();
        try{
            this.queue.add(name);
            //添加元素之后唤醒正在等待的线程
            notEmpty.signalAll();

        }finally {
            lock.unlock();
        }
    }
}


class WorkerThread extends Thread{
    TaskQueue taskQueue;
    public WorkerThread(TaskQueue taskQueue){
        this.taskQueue=taskQueue;
    }

    public void run(){
        while(!isInterrupted()){
            String name=null;
            try{
                //不断从queue中获取内容,getTask会让当前线程进入等待状态
                name=taskQueue.getTask();
            }catch (InterruptedException e){
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
            String result="Hello "+name;
            System.out.println(result);
        }
    }
}

public class ConcurrentCondition {
    public static void main(String[] args) throws Exception{
        TaskQueue taskQueue=new TaskQueue();
        WorkerThread workerThread=new WorkerThread(taskQueue);
        workerThread.start();
        taskQueue.addTask("bob");
        Thread.sleep(1000);
        taskQueue.addTask("lucy");
        Thread.sleep(1000);
        taskQueue.addTask("zhang");
        Thread.sleep(1000);
        workerThread.interrupt();
        workerThread.join();
        System.out.println("Main End");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值