前言
小編最近在學習線程的內容,發現裡面的小例子實現起來非常的有意思,當然也非常有用,線程的內容,幾乎是我們每天都會遇到,但是不是特別注意的,下面小編帶大家進一步認識線程吧。
線程和進程 1.線程是一個程式內部的順序控制流程
2.線程和進程區別:
(1)每個進程都有獨立的代碼和資料空間(進程上下文),進程間的切換會有較大的開銷;
(2)線程可以看成輕量級的進程,同一類線程共用代碼和資料空間,每個線程有獨立的運行棧和程式計數器(PC),線程切換的開銷小;
(3)多進程:在作業系統中能同時運行多個任務(程式);
(4)多線程:在同一個應用程式中有多個順序流同時執行。
線程同步
在Java語言中,引入了對象互斥鎖的概念,保證共用資料操作的完整性。
1.對象互斥鎖
每個對象都對應於一個可稱為“互斥鎖”的標記,這個標記保證在任何一時刻,只能有一個線程訪問該對象。
2.關鍵字synchronized
synchronized來與對象的互斥鎖聯絡,當某個對象用synchronized修飾時,表明該對象在任一時刻只能由一個線程訪問。
生產者和消費者的例子
1.程式碼分析
(1)共有5個類:主程式類ProducerConsumer、生產的食物類WoTou、實現線程同步的加鎖類SyncStack、生產者類Producer和消費者類Consumer
(2)Producer和Consumer實現了介面Runnable,屬於兩個線程;
(3)當在執行線程同步時,如果生產的數量超出了容器即數組的索引值6的話,則執行Object.wait()的方法,否則啟用另一個線程消費Consumer,使用Object .notify()方法。
2.代碼實現
public class ProducerConsumer { public static void main(String[] args) throws Exception{ SyncStack ss=new SyncStack(); Producer p=new Producer(ss); Consumer c=new Consumer(ss); new Thread(p).start(); new Thread(c).start(); }}class WoTou{ int id; WoTou(int id){ this.id=id; } public String toString(){ return "wotou: "+id; }}class SyncStack{ int index=0; WoTou[] arrWT=new WoTou[6]; public synchronized void push(WoTou wt){ while(index==arrWT.length){ try{ this.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } this.notify(); arrWT[index]=wt; index++; } public synchronized WoTou pop(){ while(index==0){ try{ this.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } this.notify(); index--; return arrWT[index]; }}class Producer implements Runnable{ SyncStack ss=new SyncStack(); Producer(SyncStack ss){ this.ss=ss; } public void run(){ for(int i=0;i<=20;i++){ WoTou wt=new WoTou(i); ss.push(wt); System.out.println("生產了 "+wt); try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){ e.printStackTrace(); } } }}class Consumer implements Runnable{ SyncStack ss=new SyncStack(); Consumer(SyncStack ss){ this.ss=ss; } public void run(){ for(int i=0;i<=20;i++){ WoTou wt=ss.pop(); System.out.println("消費了 "+wt); try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){ e.printStackTrace(); } } }}小結
線程同步,是在面試中經常可以會被問到的題目,這個小例子如果自己能夠動手寫出來,充分理解之後,相信會很有協助。
感謝您的訪問。