您的位置:首页 > 编程语言 > Java开发

java thread自学笔记

2012-06-01 13:02 369 查看
线程有多种写法。

第一种是实现runnable接口。

第二种是继承thread类。

第三种是直接写runnable的实现方法。

public class ThreadTest {

public static void main (String[] args) {

Runnable r = new Runnable() {
public void run() {
System.out.print("foo");
}
};
Thread t = new Thread(r);
t.run(); //output foo
t.start(); //output foo
try {
t.join(); //waiting for thread end
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Thread t1 = new Thread(r);
t1.start(); //output foo
t1.run(); //nothing output.because target(runnable is null).
}

}


如果调用两次start方法会有什么效果呢?

Thread t1 = new Thread(r);
t1.start(); //output foo
t1.start(); //threadStatus != 0(NEW) throw a IllegalThreadStateException
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: