我在Java中有一个关于线程的问题,它有一个单线程,还有一个关于停止线程并继续的问题。
我的代码做什么:类MainWindow创建一个Threadreference,并在endloop中启动和停止它。
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();
}
您不应使正在运行的线程可运行。即)您无法启动已经运行的线程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句