zoukankan      html  css  js  c++  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();
    		}
    	}
    }
    

      

  • 相关阅读:
    MediaRecorder.AudioSource参数
    putty连接服务器
    支持库
    ImageView
    .net下MD5算法和加盐
    SqlHelper文件复习
    .net下连接数据库
    Windows Server 2003 R2 64位简体中文版下载
    gacutil.exe 注册assembly
    Sharepoint Powershell
  • 原文地址:https://www.cnblogs.com/fhychzu/p/6920843.html
Copyright © 2011-2022 走看看