首页 > 开发 > Java > 正文

Java线程入门——定义线程中的 run 方法

2024-07-13 09:54:48
字体:
来源:转载
供稿:网友


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;

}

}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表