Java學習(九):Java線程的兩種實現方式

來源:互聯網
上載者:User

標籤:

  線程是程式中一個單一的順序控制流程程。進程內一個相對獨立的、可調度的執行單元,是系統獨立調度和指派CPU的基本單位指運行中的程式的調度單位。在單個程式中同時運行多個線程完成不同的工作,稱為多線程。

  進程(Process)是電腦中的程式關於某資料集合上的一次運行活動,是系統進行資源分派和調度的基本單位,是作業系統結構的基礎。

  Java線程建立的兩種方式:

1.繼承Thread類

public class MyThread extends Thread{    private String name;        public MyThread(String name)    {        this.name = name;    }        public void run()    {        try        {            for (int i = 0; i < 5; i++)            {                Thread.sleep(100); // 增加代碼執行時間                System.out.println("Thread " + this.name + ":" + i);            }        }        catch (InterruptedException e)        {            e.printStackTrace();        }    }        public static void main(String[] args)    {        Thread thread1 = new MyThread("one");        Thread thread2 = new MyThread("two");        thread1.start();        thread2.start();    }}

輸出結果:

Thread one:0Thread two:0Thread two:1Thread one:1Thread one:2Thread two:2Thread one:3Thread two:3Thread one:4Thread two:4

 

2.實現介面Runnable

 1 public class MyThread2 implements Runnable 2 { 3     private String name; 4      5     public MyThread2(String name) 6     { 7         this.name = name; 8     } 9     10     public void run()11     {12         try13         {14             for (int i = 0; i < 5; i++)15             {16                 Thread.sleep(100); // 增加代碼執行時間17                 System.out.println("Thread " + this.name + ":" + i);18             }19         }20         catch (InterruptedException e)21         {22             e.printStackTrace();23         }24     }25     26     public static void main(String[] args)27     {28         Thread thread1 = new Thread(new MyThread2("one"));29         Thread thread2 = new Thread(new MyThread2("two"));30         thread1.start();31         thread2.start();32     }33 }

輸出結果同上。

 

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.