网站:
JavaEye
作者:
iwinyeah
链接:
http://iwinyeah.javaeye.com/blog/172200
发表时间: 2008年03月15日
声明:本文系JavaEye网站发布的原创博客文章,未经作者书面许可,严禁任何网站转载本文,否则必将追究法律责任!
我以前在其他地方发过的贴子,这几种方式都没问题,哪种较好或者说在什么情况下用哪种方法较好呢?
// 方法一
public class firstManager implements Runnable {
public void runTask() {
(new Thread(this)).start();
}
public void run() {
System.out.println("\nfirst thread method!");
// Do some thing ...
}
}
// 方法二
public class secondManager {
private BackTask backTask;
private Timer timer;
public secondManager() {
backTask = new BackTask();
timer = new Timer();
}
public void runTask() {
timer.schedule(backTask, 0);
}
private class BackTask extends TimerTask {
public void run() {
System.out.println("\nsecond thread method!");
// Do some thing ...
}
}
}
// 方法三
public class thirdManager {
private BackTask backTask;
private int cmd = 0;
public thirdManager() {
backTask = new BackTask();
backTask.start();
}
public void runTask() {
synchronized (backTask) {
cmd = 1;
backTask.notify();
}
}
private class BackTask extends Thread {
public void run() {
while (true) {
try {
if (cmd == 0) {
synchronized (this) {
wait();
}
continue;
}
System.out.println("\nthird thread method!");
// Do some thing ...
} catch (Exception e) {
}
cmd = 0;
}
}
}
}
// 用例
public void main(){
firstManager man1 = new firstManager();
secondManager man2 = new secondManager();
thirdManager man3 = new thirdManager();
man1.runTask();
man2.runTask();
man3.runTask();
}
本文的讨论也很精彩,浏览讨论>>
JavaEye推荐
文章来源:
http://iwinyeah.javaeye.com/blog/172200