Java中的线程问题

来源:百度知道 编辑:UC知道 时间:2024/06/08 23:16:32
public class ThreadTerminate {
public static void main(String args[ ]) throws Exception{

int i=0;
Hello h = new Hello();

Thread t = new Thread( h);
t.setPriority(Thread.MAX_PRIORITY);
t.start( );

System.out.println("Please stop saying Hello and say good morning!");
h.stopRunning();

while( i<5){

System.out.println("Good Morning"+i++);

}

}
}

class Hello implements Runnable{

int i = 0;
private boolean timeToQuit = false;

public void run( ){
while(!timeToQuit){

System.out.println(" Hello"+i++);
try{
if (i%2 == 0 )
Thread.sleep(10);

} catch(Exception e){ }

}
}

public void stopRunning( ){
timeToQuit = true ;
}
}<

public void stopRunning( ){
timeToQuit = true ;

这个是控制线程的,和上面的while(!timeToQuit){ 有关
因为当timeToQuit不等于true的时候线程才运行,所以public void stopRunning( ){ 这个方法是用来控制线程停下来的

为什么会停呢?就是因为运行了 stopRunning这个方法啊,而停的时候刚好就是i=3的情况,假如你的机性能特别特别差的话就可能出现hello4或者hello5之类的情况咯

budong