————————————————————————————————————
————————————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线程结束时,程序还未终止,原因是Thread1的线程调用wait方法,进入对象的等待队列中,需要notify方法将它唤醒
}
catch(Exception e)
{
//e.printStackTrace();
if(bStop)
return;
}
System.out.println(getName());
}
}
public void stopThread()
{
bStop=true;
}
}