欢迎光临
我们一直在努力

Java线程入门——定义线程中的 run 方法-JSP教程,Java技巧及代码

建站超值云服务器,限时71元/月

run 方法是运行线程时需要执行的代码。(你要用代码——也就是 run() 方法——来描述一个处理过程,而不是创建一个表示这个处理过程的对象。在如何理解线程方面,一直存在着争议。这取决于,你是将线程看作是对象还是处理过程。如果你认为它是一个处理过程,那么你就摆脱了“万物皆对象”的 oo 教条。但与此同时,如果你只想让这个处理过程掌管程序的某一部分,那你就没理由让整个类都成为 runnable 的。有鉴于此,用内部类的形式将线程代码隐藏起来,通常是个更明智的选择。来自tij3。)

在 java 语言中,我们可以通过下列两种方式来实现我们的run 方法:

1、覆盖 java.lang.thread 的 public void run() 方法。

public class simplethread extends thread {

public simplethread(string str) {

super(str);

}

public void run() {

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

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

try {

sleep((long) (math.random() * 1000));

} catch (interruptedexception e) {

}

}

system.out.println("done! " + getname());

}

}

调用上面定义的线程:

public class twothreadsdemo {

public static void main(string[] args) {

new simplethread("jamaica").start();

new simplethread("fiji").start();

}

}

2、实现 java.lang.runnable 接口:

import java.awt.graphics;

import java.util.*;

import java.text.dateformat;

import java.applet.applet;

public class clock extends applet implements runnable {

private thread clockthread = null;

public void start() {

if (clockthread == null) {

clockthread = new thread(this, "clock");

clockthread.start();

}

}

public void run() {

thread mythread = thread.currentthread();

while (clockthread == mythread) {

repaint();

try {

thread.sleep(1000);

} catch (interruptedexception e) {}

}

}

public void paint(graphics g) {

calendar cal = calendar.getinstance();

date date = cal.gettime();

dateformat dateformatter = dateformat.gettimeinstance();

g.drawstring(dateformatter.format(date), 5, 10);

}

public void stop() {

clockthread = null;

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Java线程入门——定义线程中的 run 方法-JSP教程,Java技巧及代码
分享到: 更多 (0)

相关推荐

  • 暂无文章