Discuss / Java / demo

Loading...

#1 Created at ... [Delete] [Delete and Lock User]
public class WaitNotify {
    public static void main(String[] args) throws InterruptedException {

        TaskQueue q = new TaskQueue();
        ArrayList<Thread> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(() -> {
                try {
                    String task = q.getTask();
                    System.out.println(task);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
            list.add(t);
        }
        Thread add = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                String s = "t" + Math.random();
                q.addTask(s);
            }
        });
        add.start();
        add.join();

    }
}

class TaskQueue {
    Queue<String> queue = new LinkedList<>();
    private  final Lock lock=new ReentrantLock();
    private final Condition condition=lock.newCondition();
    public  void addTask(String s) {
        lock.lock();
        try {
            queue.add(s);
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }

    public  String getTask() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()){
               condition.await();
            }
        }finally {
            lock.unlock();
        }

        return queue.remove();
    }
}

不器

#2 Created at ... [Delete] [Delete and Lock User]

拿到锁还没执行操作就释放了


  • 1

Reply