/*代码原意是Game线程每隔0.3秒钟给int变量head加一,然后打印出来;TimeCounter线程在第1.5秒钟使Game线程等待3秒钟,然后Game线程重新运行,可是我的程序在运行时候Game线程并没有等待3秒钟,为什么呢?*/
class TimeCounter extends Thread {
Game game;
TimeCounter(Game g) {
game = g;
}
public void run() {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (game != null)
game.stop();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (game != null)
game.resume();
}
}
class Game implements Runnable {
// 只写重要的代码
int head;
Thread thread;
public void run() {
while (true) {
head++;
System.out.println(head);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() {
try {
thread.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void resume() {
thread.notify();
}
public static void main(String[] args) {
Game game = new Game();
TimeCounter tc = new TimeCounter(game);
game.start();
tc.start();
}
}
------解决方案--------------------
在TimeCounter线程中调用了game.stop()无形中是要让TimeCounter线程wait
可在Game类线程的运行模块中设置
- Java code
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();