Java 如何使对象等待几毫秒,然后在等待期间取消活动等待?

Java 如何使对象等待几毫秒,然后在等待期间取消活动等待?,java,multithreading,locking,Java,Multithreading,Locking,我想让一个物体等待一段时间。在此期间,对象可能被锁定,无法处理任何命令。等待活动可以在等待期间取消 首先,我尝试了以下方法,这是一个简单的方法: public void toWaiting(int waitingTime) { synchronized(this) // this is the reference for the current object { try { this.wait(waitingTime);

我想让一个物体等待一段时间。在此期间,对象可能被锁定,无法处理任何命令。等待活动可以在等待期间取消

首先,我尝试了以下方法,这是一个简单的方法:

public void toWaiting(int waitingTime)
{
    synchronized(this) // this is the reference for the current object
    {
        try {
            this.wait(waitingTime);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}
它可以工作,当前对象可能会被阻止等待,但我无法在等待期间取消此等待活动

所以我试着用线程来处理这个问题。将wait方法放入线程中,然后通过调用thread.interrupt()取消等待活动。我写了以下代码:

public void toWaiting(int waitingTime) 
{
    robotWaitTask waitingTask = new robotWaitTask(waitingTime);
    waitingTask.start();
}

// Generate a thread which could cause the object waiting for a interval
class robotWaitTask extends Thread 
{
    int waitingTime;

    public robotWaitTask(int waitingTime)
    {
        this.waitingTime = waitingTime;
    }

    public void run()
    {
        synchronized(this)
        {
            try {
                this.wait(waitingTime);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
上述操作不起作用,因为当前对象未被阻止,除非我将waitingTask.start()更改为waitingTask.run()(我不知道为什么,没有例外)。我知道调用run方法不会导致新线程的生成,它只是一个直接调用。所以,如果我使用waitingTask.run(),那么中断()方法无法取消任何线程


如何解决我的问题?

您的代码应该正常工作。您说过除非更改为使用.run(),否则当前对象不会被阻止。如果调用.run(),则表示该方法在当前线程中执行,而不是在单独的线程中执行。这可能就是你“注意到”它被阻塞的原因。 如果使用.start(),将创建一个单独的线程,并在该单独线程中阻止该对象。同时,主线程将继续执行

robotWaitTask waitingTask = new robotWaitTask(1000);
waitingTask.start(); //start a new thread, and the object is blocked in a separate thread
//this line will print as soon as the previous line called even before 1000ms
System.out.println("here)"; 


robotWaitTask waitingTask = new robotWaitTask(1000);
waitingTask.run();
//this line will print after 1000ms because the object is blocked in this thread
System.out.println("here)"; 

您在哪里调用waitingTask.interrupt()?您没有使用您应该使用的wait,中断不是用来唤醒线程,而是用来停止它。阅读有关并发性的教程:。wait方法的javadoc还有有用的信息:@Tudor我只需编写一个新方法来调用waitingTask.interrupt(),当然,我必须将waitingTask实例更改为全局变量。但是第一个问题是waitingTask.start()不工作。@Miles Zhang:你说的“不工作”是什么意思?run方法没有执行吗?@JBNizet我没有使用中断来唤醒线程,我使用它来停止线程。谢谢你的回答!你是对的,我阻塞了主线程,然后我认为当前对象正在阻塞。。。