threadtest1.java
来自「孙鑫JAVA从入门到精通配套练习程序。所有程序都实际运行过」· Java 代码 · 共 59 行
JAVA
59 行
//演示如何终止一个线程
class ThreadTest1
{
public static void main(String[] args)
{
MyThread1 mt = new MyThread1();
mt.start();
int index = 0;
while(true)
{
if (index++ == 50)
{
System.out.println("Before MyThread1 stopThread method is called!");
mt.stopThread();
System.out.println("After MyThread1 stopThread method is called!");
}
if (index == 60)
{
break;
}
System.out.println(Thread.currentThread().getName());
}
System.out.println("main is stopped!");
}
}
class MyThread1 extends Thread
{
boolean bStop = false;
public void run()
{
while (!bStop)
{
try
{
System.out.println("MyThread is waited!");
wait();
}
catch(InterruptedException ex)
{
}
System.out.println(getName());
}
if(bStop)
{
System.out.println("MyThread1 is stopped");
}
}
public void stopThread()
{
System.out.println("MyThread1 stopThread method is called!");
bStop = true;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?