Java線程總結(一)

來源:互聯網
上載者:User

標籤:rri   set   sleep   ack   http   new   art   方法   col   

首先,先貼上一個簡單的線程執行個體:

public class MyThread  extends Thread{    @Override    public void run(){        try {            for (int i = 0; i < 10; i++){                int time = 1000;                Thread.sleep(time);                System.out.println("run = "  + Thread.currentThread().getName());            }        }catch (InterruptedException e){            e.printStackTrace();        }    }    public static void main(String[] args) {        MyThread myThread = new MyThread();        myThread.setName("MyThread");        myThread.start();        try{            for (int i = 0; i < 10; i++){                int time = 1000;                Thread.sleep(time);                System.out.println("main = " + Thread.currentThread().getName());            }        }catch (InterruptedException e){            e.printStackTrace();        }    }}

運行結果如下:

由運行結果可以看出,程式中有兩個線程,一個是主線程,另一個是我手動建立的線程,主線程都是jvm建立的。

線程執行start()方法不代表線程的啟動順序,如下例:

public class MyThread  extends Thread{    private int i;    public MyThread(int i){        super();        this.i = i;    }    @Override    public void run(){        System.out.println(i);    }    public static void main(String[] args) {        MyThread thread1 = new MyThread(1);        MyThread thread2 = new MyThread(2);        MyThread thread3 = new MyThread(3);        MyThread thread4 = new MyThread(4);        MyThread thread5 = new MyThread(5);        MyThread thread6 = new MyThread(6);        MyThread thread7 = new MyThread(7);        MyThread thread8 = new MyThread(8);        MyThread thread9 = new MyThread(9);        MyThread thread10 = new MyThread(10);        thread1.start();        thread2.start();        thread3.start();        thread4.start();        thread5.start();        thread6.start();        thread7.start();        thread8.start();        thread9.start();        thread10.start();    }}

運行結果如下,執行順序與調用start()方法的順序不一致:

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.