22: new ComplexThread("one potato", 1.1F);
23: new ComplexThread("two potato", 1.3F);
24: new ComplexThread("three potato", 0.5F);
25: new ComplexThread("four", 0.7F);
26: }
27: }
1.2 Runable接口
创建多线程运行指定代码的另一种方法是,在创建类时implement Runable这个接口:
public class MySecondThread extends ImportantClass implements Runnable {
public void run() {. . .}
}
说明:
(1) 该类implement Runable接口,就表明有意图运行在单独的线程中,Thread也是implement Runable接口的;
(2) Implement Runalbe接口至少需要实现run方法;
以下是创建新线程运行该类的实例:
MySecondThread aMST = new MySecondThread();
Thread aThread = new Thread(aMST);
aThread.start();
说明:
(3) Thread类有多个构造函数Thread()、Thread(Runable target)等,本例中用的就是第二个构造函数,它有一个Runable类型的函数,所 以要在多线程中运行的实例的类必须是implement Runable的;
(4) AThead.start()方法调用Thread实例的中的target.run方法,本例中就是MySecondThread实例中的run方法;
(5) Thread构造函数还可以指定线程名,运行所需的stack,线程所属的组等;
为了防止线程非正常结束,需要将start方法置入try…catch中,如:
try{
myThread.start();
}catch(ThreadDeath aTD){
System.out.println("end Thread");
throw aTD;
}
在这个例子中将捕获ThreadDeath异常,处理后重新抛出该异常,以便Java执行stop方法,进行资源等清理工作。
文章来源于领测软件测试网 https://www.ltesting.net/










