當前位置:網站首頁>多線程的實現方式

多線程的實現方式

2022-01-27 20:40:51 mikimi阿童木

1.繼承Thread,重寫run方法

class ThreadExt extends Thread {
    
    @Override
    public void run() {
    
        System.out.println("多線程"+this.getName());
        try{
    
            sleep(1000L);
            System.out.println("多線程"+this.getName()+"睡眠結束");
        }catch (Exception e) {
    

        }
    }
}

2.實現Runnable接口與,重寫run方法

class ThreadImpRunnable implements Runnable{
    
    @Override
    public void run() {
    
        System.out.println("Runnable start");
        try{
    
            Thread o = new Thread();
            o.sleep(3000L);
            System.out.println("Runnable睡眠結束");
        }catch (Exception e) {
    

        }
    }
}

3.實現Callable接口,重寫call方法

class ThreadImpCallable implements Callable<String>{
    
    @Override
    public String call()  throws Exception{
    
        System.out.println("Callable start");
        try{
    
            Thread o = new Thread();
            o.sleep(3000L);
            System.out.println("Callable睡眠結束");
        }catch (Exception e) {
    

        }
        return "callable返回值";
    }

}

主線程如何調用

public class ThreadExtend {
    

    public static void main(String[] args) throws Exception{
    
    	//1 繼承Thread
        System.out.println("主線程開始");
        ThreadExt threadExtend =  new ThreadExt();
        threadExtend.start();
        
		//2 實現Runnable接口
        Long start1 = System.currentTimeMillis();
        Thread thread = new Thread(new ThreadImpRunnable());
        thread.start();
        System.out.println("runnable執行花了"+(System.currentTimeMillis()-start1));

		//3 實現Callable接口
        Long start = System.currentTimeMillis();
        ThreadImpCallable callableDemo = new ThreadImpCallable();
        FutureTask futureTask = new FutureTask<>(callableDemo);
        Thread threadcall = new Thread(futureTask);
        threadcall.start();
        System.out.println("callable開始執行花了"+(System.currentTimeMillis()-start));
        String name = (String) futureTask.get(); //獲取返回值
        System.out.println(name);
        System.out.println("callable執行完得到結果花了"+(System.currentTimeMillis()-start));

    }
}

結論

3種多線程方式執行start之後,都是以多線程的方式同時開始的,但Callable接口想要獲取返回值,需要阻塞到方法執行完

版權聲明
本文為[mikimi阿童木]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/01/202201272040510500.html

隨機推薦