简体   繁体   English

重入锁条件

[英]Reentrant lock condition

I wanted to create class Suspender that allows to pause and resume threads anytime you want, but unfortunately nothing happened after calling condition.signalAll() .我想创建类 Suspender 允许随时暂停和恢复线程,但不幸的是在调用condition.signalAll()后什么也没发生。 Can someone tell me, what is the reason?谁能告诉我,这是什么原因?

public class Task extends Thread{

    private Suspender suspender;

    public boolean paused = false;

    public Task(Suspender suspender){
        this.suspender = suspender;
    }

    public void resumeThread(){
        suspender.resume(this);
    }

    public void run(){
        System.out.println("Pausing");
        paused = true;
        suspender.pause(this);
        System.out.println("Resumed");
    }
}

public class Suspender{

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void pause(Task current) {
        try{
            lock.lock();
            while(current.paused){
                condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            lock.unlock();
        }
    }

    public void resume(Task current) {
        try{
            lock.lock();
            current.paused = false;
            condition.signalAll();
        }finally{
            lock.unlock();
        }
    }

}

public class Start{

    public static void main(String args[]) throws Exception {
        Suspender suspender = new Suspender();

        Task t1 = new Task(suspender), t2 = new Task(suspender);
        t1.start();
        t2.start();

        TimeUnit.SECONDS.sleep(2);
        t1.resume();
        TimeUnit.SECONDS.sleep(2);
        t2.resumeThread();

        t2.join();
    }

}

Your main thread calls t1.resume() , but your Task class declares public void resume(Task current) .您的主线程调用t1.resume() ,但您的Task类声明public void resume(Task current) Those are two different methods.这是两种不同的方法。 Java allows different methods to have the same name if they have different argument lists.如果具有不同的参数列表,Java 允许不同的方法具有相同的名称。 When your main thread calls t1.resume() it is calling a deprecated method of the Thread class , which will have no effect because the thread never was suspended.*当您的主线程调用t1.resume()它正在调用Thread不推荐使用的方法,这将不起作用,因为线程从未被挂起。 *


* Note: suspended is not the same thing as awaiting a condition. * 注意: 暂停与等待条件不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM