1. 程式人生 > >執行緒的三種實現方法

執行緒的三種實現方法

執行緒的三種實現方法:
(1)繼承 Thread 類,重寫run()方法;

(2)實現 Runnable 介面,重寫run() 方法;

(3)實現 Callable 介面,重寫call()方法;

方式一:  繼承Thread類

public class MyThreadDemo
{
    public static void main(String[] args)
    {
        Thread thread = new MyThread();
        thread.start();
    }
}

class MyThread extends Thread
{
    @Override
    
public void run() { System.out.println("extends Thread"); } }

方式二: 實現 Runnable 介面

public class MyRunnableDemo
{
    public static void main(String[] args)
    {
        //方法一
        Thread thread = new Thread(new MyRunnable());
        thread.start(); //啟動執行緒

        //方法二 匿名類
        Thread thread1 = new
Thread(new Runnable() { @Override public void run() { System.out.println("anonymous class implement Runnable"); } }); thread1.start(); //啟動執行緒 } } class MyRunnable implements Runnable { @Override public
void run() { System.out.println("implement Runnable"); } }

方式三: 實現 Callable 介面

Callable 的 call() 方法會返回執行結果,丟擲異常;

ExecutorService :執行緒池的介面;

Executors: 執行緒池的工具類

 

public class MyCallableDemo
{
    public static void main(String[] args) throws ExecutionException, InterruptedException
    {
        //方法一  使用執行緒池方式
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future future = executorService.submit(new MyCallable());
        future.isDone();      //return true,false 無阻塞
        System.out.println(future.get());    // return 返回值,阻塞直到該執行緒執行結束

        //方法二
        FutureTask futureTask = new FutureTask(new MyCallable());
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
    }
}

class MyCallable implements Callable
{
    @Override
    public String call() throws Exception
    {
        System.out.println(Thread.currentThread().getName() + ": 執行 Call 方法");
        return Thread.currentThread().getName() + "執行緒執行完成";
    }
}

執行結果: 

  

 

FutureTask 類實現了 Runnable 介面