日期:2014-05-20 浏览次数:20835 次
if (isStopped) {
try {
synchronized (thread) {
thread.wait();
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
------解决方案--------------------
在一个线程里是不能直接控制另外一个线程的运行状态,你只能通过设置状态标志的方式来间接控制。
class TimeCounter extends Thread
{
Game game;
TimeCounter(Game g)
{
game = g;
}
public void run()
{
try
{
Thread.sleep(1500);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
if(game != null)
{
game.setStop(true);
}
}
}
class Game implements Runnable
{
// 只写重要的代码
int head;
boolean stop;
Thread thread;
public void run()
{
while(true)
{
synchronized(this)
{
head++;
System.out.println(head);
try
{
if(stop)
{
this.wait(3000);
stop = false;
}
Thread.sleep(300);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
public void start()
{
thread = new Thread(this);
thread.start();
}
public void setStop(boolean stop)
{
this.stop = stop;
}
public static void main(String[] args)
{
Game game = new Game();