服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

最简单的编写基于线程的代码的方法之一:派生线程类

派生线程类

最简单的编写基于线程的代码的方法之一,就是派生java.lang.thread 类。该线程类是java.lang 包的一个成员,在缺省情况下,线程类可以被所有的java应用程序调用。为了使用线程类,我们需要了解the java.lang.thread 类中定义的五个方法:

run():该方法用于线程的执行。你需要重载该方法,以便让线程做特定的工作。

start():该方法使得线程启动run()。

stop():该方法同start方法的作用相反,停止线程的运行。

suspend():该方法同stop方法不同的是,它并不终止未完成的线程,它仅仅挂起线程,以后还可恢复。

resume():该方法重新启动已经挂起的线程。


运行list a中的程序,运行结果见list b



list a :扩展线程类



class testthreads {

public static void main (string args []) {

class mythread extends thread {

string which;

mythread (string which) {

this.which = which;

}

public void run() {

int iterations = (int)(math.random()*100) %15;

int sleepinterval = (int)(math.random()*1000);

system.out.println(which + " running for " + iterations +" iterations");

system.out.println(which + " sleeping for " + sleepinterval + "ms between loops");

for (int i = 0; < iterations; i++) {

system.out.println(which +" " + i);

try {

thread.sleep(sleepinterval);

} catch (interruptedexception e) {}

}

}

}

mythread a = new mythread("thread a");

mythread b = new mythread("thread b");

mythread c = new mythread("thread c");

a.start();

b.start();

c.start();

}

}



listb: 清单a的输出

thread a running for 16 iterations



thread c running for 15 iterations

thread b running for 14 iterations

thread a sleeping for 305ms between

loops

thread c sleeping for 836ms between

loops

thread b sleeping for 195ms between

loops

thread a 0

thread c 0

thread b 0

. . .

thread c 13

thread b 13

thread a 14

thread c 14

thread a 15

list a演示了如何从现有的thread类中派生出一个新类。新创建的类重载了run 方法。有趣的是,实现run 方法不必很严格,因为thread类提供一个缺省的run方法,尽管它不是特别有用。
在有些场合,我们不能简单地改变指定对象的父类。我们仍然需要采用线程。这时,我们就需要用到runnable接口。

扫描关注微信公众号