我在 Java 中遇到一个关于线程的问题,它涉及单线程以及停止线程并继续。
我的代码的作用:MainWindow 类创建一个 Threadreference,并在结束循环中启动和停止它。
MyThread 类启动线程。 run 方法非常短,它所做的就是: 1.将鼠标移动到屏幕左侧 然后 2.将鼠标移动到屏幕右侧
当我启动程序时,我立即收到 IllegalMonitorStateException 并且不知道如何修复它。
public class MainWindow
{
public static void main(String[] args) throws Exception
{
MyThread mt = new MyThread();
while(true)
{
mt.start();
Thread.sleep(1000);
mt.wait();
}
}
}
public class MyThread implements Runnable
{
private Thread th;
public MyThread() throws Exception
{
th = new Thread();
th.start();
}
public void start() throws InterruptedException
{
synchronized(this){
th.wait();
}
}
public void wait()
{
synchronized(this){
th.notifyAll();
}
}
@Override
public void run()
{
//do something
}
}
感谢您的帮助! :)
最佳答案
while(true)
{
mt.start();
Thread.sleep(1000);
mt.wait();
}
您不应该使正在运行的线程可运行。即)您无法启动已经运行的线程。
关于Java 简单单线程 IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37731692/