java构造函数中启动线程_通过构造器启动线程的实现方式及其缺点记录。

说明:在构造器中启动线程会很有问题,因为另一个任务可能会在构造器结束之前开始执行,导致该任务会访问到处于不稳定状态的对象。这也是优选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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值