JAVA之線程實現方式Test代碼練習

線程實現方式有四種,大型項目基本使用線程池,簡要羅列代碼塊。

1、繼承Thread類創建線程

/**
 * @author yto_yh
 *
 */
public class TestThread090601 extends Thread{
    
    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println("線程啓動");
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread090601 t=new TestThread090601();
        TestThread090601 t1=new TestThread090601();
        t.start();
        t1.start();
    }

}

2.實現Runnable接口創建線程


/**
 * @author yto_yh
 *
 */
public class TestThread90602 implements Runnable{
    public void run() {
        System.out.println("線程啓動");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread90602 tt=new TestThread90602();
        Thread t=new Thread(tt);
        t.start();
        Thread t1=new Thread(tt);
        t1.start();
    }

}

3、使用ExecutorService、Callable、Future實現有返回結果的線程

/**
 * @author yto_yh
 *
 */
public class TestCallable0903 implements Callable<Object>{
    

    private int threadNum;
    TestCallable0903(Integer threadNum){
        this.threadNum=threadNum;
    }
    /* (non-Javadoc)
     * @see java.util.concurrent.Callable#call()
     */
    @Override
    public Object call() throws Exception {
        System.out.println("第"+threadNum+"個線程啓動!");
        return "第"+threadNum+"個線程結束!";
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int taskSize = 5;  
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);  
        List<Future> list = new ArrayList<Future>();  
        for (int i = 0; i < taskSize; i++) {  
             Callable c = new TestCallable0903(i);  
             Future f = pool.submit(c);  
             list.add(f);  
        }  
        pool.shutdown();  
        for (Future f : list) {  
            System.out.println(">>>" + f.get().toString());  
        }  
    }
}

/**
 * @author yto_yh
 *
 */
public class TestCallable90302 {

    /**
     * @param args
     * @throws ExecutionException 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
      int threadNum=3;//創建線程數量
      List<Future> list =new ArrayList<Future>();
      ExecutorService executorService=Executors.newFixedThreadPool(threadNum);//創建線程池
      for(int i=0;i<threadNum;i++) {
         //提交有返回類型的任務
         Future f= executorService.submit((Callable)(new MyCallable(i+" ")));
         list.add(f);
      }
     executorService.shutdown(); 
    //遍歷返回值
     list.forEach(s->{
        try {
            System.out.println(s.get().toString());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
      });
    }
}




/**
 * @author yto_yh
 *
 */
public class MyCallable implements Callable<Object>{
    
    private String taskNum;  
    
    MyCallable(String taskNum) {  
       this.taskNum = taskNum;  
    } 
    @Override
    public Object call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println(">>>" + taskNum + "任務啓動");  
        Date dateTmp1 = new Date();  
        Thread.sleep(1000);  
        Date dateTmp2 = new Date();  
        long time = dateTmp2.getTime() - dateTmp1.getTime();  
        System.out.println(">>>" + taskNum + "任務終止");  
        return taskNum + "任務返回運行結果,當前任務時間【" + time + "毫秒】";  
    }
  //實現call()方法,作爲線程執行體
/*    public Integer call(){
        int i = 5;
        for( ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName() + "的循環變量i的值:" +i);
        }
        //call()方法可以有返回值
        return i;
    }
    
    public static void main(String[] args) {
      //創建Callable對象
        Callable cd = new MyCallable();
        //使用FutureTask來包裝Callable對象
        FutureTask<Integer> task = new FutureTask<Integer>(cd);
        for(int i=0 ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName() + "的循環變量i的值:" +i);
            if(i==20){
                //實質還是以Callable對象來創建並啓動線程
                new Thread(task,"有返回值的線程").start();
            }
        }
        try{
            System.out.println("子線程的返回值" + task.get());
            
        }catch(Exception e){
            e.printStackTrace();
        }
*/
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章