1. 程式人生 > >Java多線程的幾種寫法

Java多線程的幾種寫法

pri tca exc exce ++ executor main方法 多線程 ext

Java多線程的在開發中用到的很多,簡單總結一下幾種寫法,分別是繼承Thread方法,實現Runnable接口,實現Callable接口;
1.繼承Thread方法

class TestThread extends Thread{
    String name;
    public TestThread(String name){
        this.name=name;
    }
    @Override
    public void run() {
        for (int i = 0; i < 6; i++) {
            System.out.println(this.name+":"+i);
        }
    }
}

main方法調用:
Thread啟動有兩個方法,一個是start()方法,一個是run()方法,但是直接調用run方法時線程不會交替運行,而是順序執行,只有用start方法時才會交替執行

TestThread tt1 = new TestThread("A");
        TestThread tt2 = new TestThread("B");
        tt1.start();
        tt2.start();

運行結果:
技術分享圖片
2.實現Runnable接口,有多種寫法
2.1外部類

class TestRunnable implements Runnable{
    String name;
    public TestRunnable(String name){
        this.name=name;
    }
    @Override
    public void run() {
        for (int i = 0; i < 6; i++) {
            System.out.println(this.name+":"+i);
        }
    }
}

調用:

   TestRunnable tr1 = new TestRunnable("C");
        TestRunnable tr2 = new TestRunnable("D");
        new Thread(tr1).start();
        new Thread(tr2).start();

2.2匿名內部類方式

new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

            }
        }).start();

2.3 Lamda表達式,jdk1.8,只要是函數式接口,都可以使用Lamda表達式或者方法引用

new Thread(()->{
        for (int i = 0; i < 6; i++) {
            System.out.println(i);
        }
    }).start();

2.4ExecutorService創建線程池的方式

class TestExecutorService implements Runnable{
String name;
public TestExecutorService(String name){
    this.name=name;
}
    @Override
    public void run() {
        for (int i = 0; i < 6; i++) {
            System.out.println(this.name+":"+i);
        }
    }
}

調用:可以創建固定個數的線程池

   ExecutorService pool = Executors.newFixedThreadPool(2);
        TestExecutorService tes1 = new TestExecutorService("E");
        TestExecutorService tes2 = new TestExecutorService("F");
        pool.execute(tes1);
        pool.execute(tes2);
        pool.shutdown();
    運行結果跟2.1差不多

技術分享圖片

3.實現Callable接口,可以返回結果

//Callable<V>提供返回數據,根據需要返回不同類型
class TestCallable implements Callable<String>{
    private int ticket = 5;
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 5; i++) {
            if(this.ticket>0)
                System.out.println("買票,ticket="+this.ticket--);
        }
        return "票賣完了";
    }
}

調用:

Callable<String> tc = new TestCallable();
        FutureTask<String> task = new FutureTask<String>(tc);
        new Thread(task).start();
        try {
            System.out.println(task.get());//獲取返回值
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    運行結果:

技術分享圖片

Java多線程的幾種寫法