1.runable我实验了一下,同时new了3个LiftOff,他们还是按照顺讯打印出来的,且线程名都是main,线程id也相同。说明直接用run方法是借用主线程来运行程序的,且会排队来运行。代码比较长,但是我没找到csdn有代码折叠功能,知道如何折叠的朋友可以留评论赐教一下哈。
package com.runnablethreads.gc;
public class LiftOff implements Runnable{
public LiftOff(){
System.out.println("thread constructor");
}
public void run(){
Thread thread = Thread.currentThread();
for(int i = 0;i<3;i++){
System.out.println("new thread"+i);
System.out.println("Thread Id: " + thread.getId());
System.out.println("Thread Name: " + thread.getName());
Thread.yield();
}
System.out.println("over");
}
}
package com.runnablethreads.gc;
public class MainThread {
public static void main(String[] args){
//for(int i = 0; i <5; i++){
//new Thread(new LiftOff()).start();
//}
LiftOff l1=new LiftOff();
l1.run();
LiftOff l2=new LiftOff();
l2.run();
LiftOff l3=new LiftOff();
l3.run();
}
}
结果:
thread constructor
new thread0
Thread Id: 1
Thread Name: main
new thread1
Thread Id: 1
Thread Name: main
new thread2
Thread Id: 1
Thread Name: main
over
thread constructor
new thread0
Thread Id: 1
Thread Name: main
new thread1
Thread Id: 1
Thread Name: main
new thread2
Thread Id: 1
Thread Name: main
over
thread constructor
new thread0
Thread Id: 1
Thread Name: main
new thread1
Thread Id: 1
Thread Name: main
new thread2
Thread Id: 1
Thread Name: main
over
2.thread我也实验了一下(new Thread(new LiftOff()).start();)同时new多个会并行,且线程名不同。
3.Runnable是一个接口,而Thread是一个类。runnable实现了接口还可以继承另一个不同的类,而thread不行。(think in java P666)
4.join方法(例子在thinkinjava P670) —A的run方法里面谢了调用B.join()的方法。则若A执行到B.join()则会挂起等待B的线程执行完毕后加入b的线程继续执行接下来的代码。
5调用A.interrupt会打断try catch里的代码,执行接下来的代码,执行完毕之后,B.join()可以顺利执行
ps:打印线程号小技巧:
Thread thread = Thread.currentThread();System.out.println(“new thread”+i);
System.out.println(“Thread Id: ” + thread.getId());
System.out.println(“Thread Name: ” + thread.getName());