標籤:
一、為什麼需要並發編程
如果是單線程的編程,如果一個程式遇到阻塞的情況,比如需要等待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