如何使用wait()和notify()正确暂停线程 [英] How do I pause Threads properly with wait() and notify()

查看:196
本文介绍了如何使用wait()和notify()正确暂停线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个启动线程并提供暂停和继续该线程的方法的类.我的第一种方法是使用flag,只要值是true,它就会循环睡眠方法.像这样的东西:

I want to have a class that starts a Thread and provides methods to pause and continue this Thread. My first approach was to have flag, which loops a sleep method as long as the value is true. Something like :

public class Bot {
private Thread t ;
private boolean isPaused;

public Bot(){
    t = new Thread(new Runnable(){
        @Override
        public void run() {
            while (true) {
                System.out.println("Hi");


                while(isPaused){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });

    t.start();
}
public void pauseBot(){
    isPaused = true;
}

public void continueBot(){
    isPaused = false;
}
}

但是,由于线程仍在运行并浪费CPU,因此我认为这不是一个好的解决方案. wait()和notify()看起来如何. 我浏览了有关该主题的各种教程,但是以某种方式我无法将它们应用于我的问题.

But since the Thread is still running and wasting CPU, I dont find this to be a good solution. How would this look with wait() and notify(). I had a look at various tutorials about that topic but somehow I couldnt apply them to my issue.

每次尝试时,我要么收到IllegalMonitorStateException,要么代码停止了我的整个应用程序,而不仅仅是停止了我想停止的线程.

Everytime I tried it I either got IllegalMonitorStateException or the code stopped my whole application and not just the Thread I wanted to be stopped.

我的另一个问题是:如何防止线程在关键时刻暂停蜂鸣,例如

Another question I have is: How do prevent the Thread from beeing paused at a critical moment e.g.

Runnable r = new Runnable(){

    @Override
    public void run() {
        while(true){
            task1();
            task2();

            //Thread mustn't be stopped from here....
            task3();
            task4();
            task5();
            task6();
            task7();
            //... to here

            task8();
            task9();
            task10();
        }

    }

};

因为当task3().... task7()处理线程暂停时可能过期的东西时,必须有一种方法让线程完成task7()直到暂停.

Because when task3() .... task7() deal with something that would expire while the Thread is paused there must be a way to let the Thread finish task7() until it pauses.

希望您能帮助我解决我的问题. 提前致谢, Flo

I hope you can help me with my issue. Thanks in advance, Flo

推荐答案

因此,这是您的Thread类:

So given this is your Thread class:

public class MyThread extends Thread
{

首先,您需要一个锁对象.该对象可以是所有对象,如果使用现有对象,则占用的内存更少.还应定义是否应暂停漫游器的标志.

First, you need an lock object. This object can be everything, and if you use an existing object this takes less memory. Also define a flag if the bot should be paused.

    public Object lock = this;
    public boolean pause = false;

现在,为线程定义一个pause()continue()方法.这将设置pause标志.

Now, define a pause() and continue() method for the thread. This sets the pause flag.

    public void pause ()
    {
        pause = true;
    }

    public void continue ()
    {
        pause = false;

在这里您需要唤醒线程.注意锁对象上的同步对象,这样您就不会得到IllegalMonitorStateException.

Here you need to wake up the thread. Note the synchronized on the lock object so that you don't get an IllegalMonitorStateException.

        synchronized (lock)
        {
            lock.notifyAll();
        }
    }

否,请定义一种在应暂停线程时自动暂停线程的方法.您可以在线程可以暂停的任何时候调用此方法.

No, define a method that automatically pauses the thread when it should be paused. You might call this at every moment when the thread can be paused.

    private void pauseThread ()
    {
        synchronized (lock)
        {
            if (pause)
                lock.wait(); // Note that this can cause an InterruptedException
        }
    }

现在,您可以在run()方法中定义线程:

Now, you can define your thread in the run() method:

    public void run ()
    {
        task1();
        task2();

        pauseThread();

        task3();
        task4();
        task5();
        task6();
        task7();

        pauseThread();

        task8();
        task9();
        task10();
    }
}

这篇关于如何使用wait()和notify()正确暂停线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆