繁体   English   中英

无法.stop().wait()或以任何方式停止线程

[英]Cannot .stop() .wait() or stop the thread in any way

我在使用JButton上的actionPerformed停止从类外部启动的线程时遇到麻烦。 下面的线程类的代码。

public synchronized void run ()
{
    try
    {
        do
        {
            int minuta = vrijeme / 60;
            int sekundi = vrijeme % 60;

            System.out.println(minuta+" "+sekundi);

            vrijeme = vrijeme - 1;
            delay = delay - 1000;

            if (minuta == stani && sekundi == 0)
            {

            }



            try 
            {
                Thread.sleep(1000);
            } 
            catch (InterruptedException e) 
            {
                e.printStackTrace();
            }
        }
        while (delay != 0);
        {
                //
        }
    }
    catch (Exception e)
    {
        System.out.println("Stao" + e);
    }
}
void pokreniThread()
{
    (new Thread(new OdredenoVrijeme())).start();
}
synchronized public void zaustaviThread()
{
    try
    {
        (new Thread(new OdredenoVrijeme())).wait();
    }
    catch (Exception e)
    {
        System.out.println("stao" +e);
    }
}

}

每次我调用.sleep() .wait()或类似方法时,都会收到以下捕获消息:

java.lang.IllegalMonitorStateException

在Java下,您无法在主进程中入睡。 创建一个子线程,该子线程将进行睡眠,然后将一条消息发布到主线程中的处理程序,以在超时后执行某些操作。

如果要停止线程本身,请在线程内部设置一个变量,例如is_stopping = true,然后在线程内部停止线程之后,可以设置变量is_running = false。

is_running=true;
while (is_running & !is_stopping)
{
   do_something();
   sleep();
}
is_stopping=false;
is_running=false;

在Java中,主线程在程序中扮演调度程序的角色。 因此,在多线程情况下,您具有以下部分:

  • 调度器/控制器
  • 提供商
  • 顾客

主线程应始终扮演程序的调度程序/控制器部分。 顺便说一句,您不是很好地使用多线程。 在绝对必要时使用同步。 看下面的代码。 您应该像这样使用同步:

public class BlockingQueue<T> {

private Queue<T> queue = new LinkedList<T>();
private int capacity;

public BlockingQueue(int capacity) {
    this.capacity = capacity;
}

public synchronized void put(T element) throws InterruptedException {
    while(queue.size() == capacity) {
        wait();
    }

    queue.add(element);
    notify(); // notifyAll() for multiple producer/consumer threads
}

public synchronized T take() throws InterruptedException {
    while(queue.isEmpty()) {
        wait();
    }

    T item = queue.remove();
    notify(); // notifyAll() for multiple producer/consumer threads
    return item;
}

您无法从外部上下文中停止线程。 当某些条件改变时,线程应自行停止。 您必须在要停止的线程中保留一个标志,然后该线程在循环中检查该标志。 如果该标志被更改,则线程本身不应该执行任何操作,它将自行退出

暂无
暂无

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

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