【Java开源代码栏目提醒】:网学会员--在 Java开源代码编辑为广大网友搜集整理了:WaitThreadStop.java绩等信息,祝愿广大网友取得需要的信息,参考学习。
package Chapter10;
//文件:
程序10.8 WaitThreadStop.java 描述:等待一个线程的结束的两种方法
class WaitThreadStop extends Thread{
//声明,并实现WaitThreadStop无参数构造方法
WaitThreadStop(){}
//声明,并实现带有一个字符串参数的构造方法
WaitThreadStop(String szName)
{
super(szName); //调用父类的构造方法
}
// 重载run函数
public void run()
{
for (int count = 1,row = 1; row < 10; row++,count++)
{
for (int i = 0; i < count; i++)
{
System.out.print('*'); //输出*
}
System.out.println(); //输出换行符
}
}
}
class WaitThreadStopMain{
public static void main(String argv[]){
WaitThreadStopMain test = new WaitThreadStopMain(); //创建,初始化WaitThreadStopMain对象test
test.Method1(); //调用Method1方法
// test.Method2();
}
//第一种方法:while/isAlive/sleep
public void Method1(){
WaitThreadStop th1 = new WaitThreadStop(); //创建,并初始化WaitThreadStop对象th1
WaitThreadStop th2 = new WaitThreadStop(); //创建,并初始化WaitThreadStop对象th2
// 执行第一个线程
th1.start();
//
查询第一个线程的状态
while(th1.isAlive()){
try{
Thread.sleep(100); //休眠100毫秒
}catch(InterruptedException e)
{
e.printStackTrace(); //异常信息输出
}
}
// 当第一个线程终止后,运行第二个线程
th2.start(); //启动线程th2
}
//第二种方法,使用join方法实现等待其他线程结束
public void Method2(){
WaitThreadStop th1 = new WaitThreadStop(); //创建,并初始化WaitThreadStop对象th1
WaitThreadStop th2 = new WaitThreadStop(); //创建,并初始化WaitThreadStop对象th2
// 执行第一个线程
th1.start();
try{
th1.join(); //th1调用join方法
}catch(InterruptedException e)
{
e.printStackTrace(); //异常信息输出
}
// 执行第二个线程
th2.start();
}
}