——————TestThread.java——————
class TestThread
{
public static void main(String[] args)
{
Thread1 t1=new Thread1();
t1.start();
int index=0;
while(true)
{
if(index++==500)
{
t1.stopThread();
t1.interrupt(); //讓線程1終止。
break;
}
System.out.println(Thread.currentThread().getName());
}
System.out.println("main() exit");
}
}
class Thread1 extends Thread
{
private boolean bStop=false;
public synchronized void run()
{
while(!bStop)
{
try
{
wait(); //加入wait后,main線程結(jié)束時(shí),程序還未終止,原因是Thread1的線程調(diào)用wait方法,進(jìn)入對象的等待隊(duì)列中,需要notify方法將它喚醒。
}
catch(Exception e)
{
//e.printStackTrace();
if(bStop)
return;
}
System.out.println(getName());
}
}
public void stopThread()
{
bStop=true;
}
}