现在的位置: 首页 > 综合 > 正文

java thread自学笔记

2013年10月13日 ⁄ 综合 ⁄ 共 594字 ⁄ 字号 评论关闭

线程有多种写法。

第一种是实现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
 		

抱歉!评论已关闭.