java並發編程——基本線程機制1

來源:互聯網
上載者:User

標籤:

一、為什麼需要並發編程

如果是單線程的編程,如果一個程式遇到阻塞的情況,比如需要等待i/o的某個事件發生,才能執行程式。這樣就造成了影響了下面的程式的運行。

並發,就是在進程中,採用多個任務進行處理,每個任務由作業系統來回切換。

這樣就感覺像很多任務同時執行一樣。

二、基本的線程機制

1、定義任務

定義一個類,實現Runnable()介面,在Runnable()介面中定義了run()方法,我們可以把要執行的事件寫在run()方法中。

而run()中任務的運行,需要將其放在Thread構造器中。

通過start方法運行thread後,就會運行在thread中的任務。

class task1 implements Runnable{    public void run()   {   for(int x=0;x<=10;x++)   {   for(int y=0;y<=99999999;y++){}System.out.println(Thread.currentThread().getName()+"....x="+x);   }  }   }class task2 implements Runnable{    public void run()   {   for(int z=0;z<=10;z++)   {   for(int y=0;y<=99999999;y++){}System.out.println(Thread.currentThread().getName()+"....z="+z);   }  }   }public class hello {public static void main(String[] args){task1 t1= new task1(); task2 t2 = new task2();Thread nt1 = new Thread(t1);Thread nt2 = new Thread(t2);nt1.start();nt2.start();}}


java並發編程——基本線程機制1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.