Java多線程系列一——Java實現線程方法

來源:互聯網
上載者:User

標籤:blog   join()   junit   啟動   script   public   啟動方式   code   依賴   

Java實現線程的兩種方法

  • 繼承Thread類
  • 實現Runnable介面

它們之間的區別如下:

1)Java的類為單繼承,但可以實現多個介面,因此Runnable可能在某些情境比Thread更適用
2)Thread實現了Runnable介面,並且有更多實用方法
3)實現Runnable介面的線程啟動時仍然需要依賴Thread

import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import org.junit.Assert;import org.junit.Test;/** * @Description: 線程的兩種實現方法 */public class ThreadImplementTest {    private Map<Integer, Long> map = new ConcurrentHashMap<>();    class MethodOne extends Thread {        private int count = 0;        @Override        public void run() {            map.put(++count, this.getId());        }    }    class MethodTwo implements Runnable {        private int count = 0;        @Override        public void run() {            map.put(++count, Thread.currentThread().getId());        }    }    @Test    public void textThread() {        /**         * 方法一:繼承Thread         */        MethodOne extendsThread = new MethodOne();        extendsThread.start();        /**         * 方法二:實現Runnable         */        MethodTwo implementsRunnable = new MethodTwo();        new Thread(implementsRunnable).start();    }    @Test    public void testTwoRuns() throws InterruptedException {        /**         * 注意:以下兩種方法啟動方式截然不同         */        Thread tmp;        MethodOne extendsThread = new MethodOne();        for (int i = 0; i < 3; i++) {// 只有一個線程            tmp = new Thread(extendsThread);            tmp.start();            tmp.join();        }        Assert.assertTrue(map.containsKey(3));        Assert.assertTrue(map.containsKey(2));        Assert.assertTrue(map.containsKey(1));        map.clear();// 清空緩衝        for (int i = 0; i < 3; i++) {// 三個不同線程            tmp = new MethodOne();            tmp.start();            tmp.join();        }        Assert.assertEquals(1, map.size());        Assert.assertTrue(map.containsKey(1));    }}

 

Java多線程系列一——Java實現線程方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.