说明:在构造器中启动线程会很有问题,因为另一个任务可能会在构造器结束之前开始执行,导致该任务会访问到处于不稳定状态的对象。这也是优选Executor而不是显示创建Thread对象的原因。
如下俩种实现方式(来自Thinking in Java 的范例),这里有个疑问:是谁调用了toString 方法??从而输出相应的内容??求解。
1.
public class SimpleThread extends Thread{
private int countDown = 5;
private static int threadCount = 0;
public SimpleThread(){
super(Integer.toString(threadCount));
start();
}
public String toString(){
return "#"+getName()+"("+countDown+")";
}
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0){
return;
}
}
}
public static void main(String[] args) {
for(int i=0;i<5;i++){
new SimpleThread();
}
}
}
2.
package zipDemo;
public class SelfManaged implements Runnable{
private int coutdown = 5;
//当写成这样的时候 private Thread t = new Thread(); 当前线程不会在控制台输出。
private Thread t = new Thread(this);
public SelfManaged() {
t.start();
}
public String toString(){
return Thread.currentThread().getName() + "("+coutdown+")";
}
@Override
public void run() {
while(true){
System.out.println(this);
if(--coutdown == 0){
return;
}
}
}
public static void main(String[] args){
for(int i=0;i<5;i++){
new SelfManaged();
}
}
}