成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Java并發編程之同步互斥問題

開發 后端
在操作系統中 同步與互斥是一個重要問題,這里主要研究一下怎樣用Java來實現操作系統中的一些同步互斥算法。

在操作系統中同步與互斥是一個重要問題,這里主要研究一下怎樣用Java來實現操作系統中的一些同步互斥算法。

1、軟件實現臨界區域問題

在《操作系統概念(第七版)》中,7.2討論了臨界區域問題,下面給出算法和Java實現代碼。

1.1 算法2

算法2的偽代碼如下:

  1. do{  
  2.  flag[i]=true;  
  3.  while(flag[j]);  
  4.  臨界區;  
  5.  flag[i]=false;  
  6.  剩余區;  
  7. }while(1

Java實現代碼如下:

  1. package mutiple_thread;  
  2.  
  3. public class OS_SYN_A2{  
  4.     public static  int flag[]=new int [3];  
  5.     public static int cnt=0;  
  6.     public static void main(String args[]){  
  7.         class proo implements Runnable{  
  8.             public proo(){  
  9.                   
  10.             }  
  11.             @Override 
  12.             public void run() {  
  13.                 // TODO Auto-generated method stub  
  14.                 while(true){  
  15.                     flag[1]=1;  
  16.                     while(flag[2]==1){  
  17.                           
  18.                     }  
  19.                     if(cnt==5){  
  20.                         flag[1]=0;  
  21.                     }else{  
  22.                         cnt++;  
  23.                         System.out.println("pro ++! now id"+cnt);  
  24.                         flag[1]=0;  
  25.                     }  
  26.                 }  
  27.             }  
  28.               
  29.         }  
  30.  
  31.         class conn implements Runnable{  
  32.  
  33.             @Override 
  34.             public void run() {  
  35.                 // TODO Auto-generated method stub  
  36.                 while(true){  
  37.                     flag[2]=1;  
  38.                     while(flag[1]==1){  
  39.                           
  40.                     }  
  41.                     //臨界區  
  42.                     if(cnt==0){  
  43.                         flag[2]=0;  
  44.                     }else{  
  45.                         cnt--;  
  46.                         System.out.println("con --! now id"+cnt);  
  47.                         //退出臨界區  
  48.                         flag[2]=0;  
  49.                     }  
  50.                 }  
  51.             }  
  52.         }  
  53.         new Thread(new proo()).start();  
  54.         new Thread(new conn()).start();  
  55.     }  
  56.       

這個算法的主要思路是通過設置flag來確定執行哪個線程,但是可能會造成饑餓,因此不行。

1.2 算法3

算法3通過共享兩個變量 flag 和turn來實現同步。

  1. package mutiple_thread;  
  2.  
  3. public class OS_SYN_A3{  
  4.     public static  int flag[]=new int [3];  
  5.     public static int turn=0;  
  6.     public static int cnt=0;  
  7.     public static void main(String args[]){  
  8.         class proo implements Runnable{  
  9.             public proo(){  
  10.                   
  11.             }  
  12.             @Override 
  13.             public void run() {  
  14.                 // TODO Auto-generated method stub  
  15.                 while(true){  
  16.                     flag[1]=1;  
  17.                     turn=2;  
  18.                     while(flag[2]==1&&turn==2){  
  19.                           
  20.                     }  
  21.                     if(cnt==5){  
  22.                         flag[1]=0;  
  23.                     }else{  
  24.                         cnt++;  
  25.                         System.out.println("pro ++! now id"+cnt);  
  26.                         flag[1]=0;  
  27.                     }  
  28.                 }  
  29.             }  
  30.               
  31.         }  
  32.  
  33.         class conn implements Runnable{  
  34.  
  35.             @Override 
  36.             public void run() {  
  37.                 // TODO Auto-generated method stub  
  38.                 while(true){  
  39.                     flag[2]=1;  
  40.                     turn=1;  
  41.                     while(flag[1]==1&&turn==1){  
  42.                           
  43.                     }  
  44.                     //臨界區  
  45.                     if(cnt==0){  
  46.                         flag[2]=0;  
  47.                     }else{  
  48.                         cnt--;  
  49.                         System.out.println("con --! now id"+cnt);  
  50.                         //退出臨界區  
  51.                         flag[2]=0;  
  52.                     }  
  53.                 }  
  54.             }  
  55.         }  
  56.         new Thread(new proo()).start();  
  57.         new Thread(new conn()).start();  
  58.     }  
  59.       

這是一種正確的軟件實現方法。

2、經典同步問題的Java實現

2.1 讀者寫者問題

這里實現的讀者優先的算法,使用了Java并發包的信號量來實現。

實現的偽代碼如下:

讀者進程:

  1. while1){  
  2.  wait(mutex)  
  3.    count++;  
  4.    if(readercount==1){  
  5.    wait(writer);   
  6.  }  
  7. signal(mutex);  
  8. do reading;  
  9. wait(mutex);  
  10. cnt--;  
  11. if(cnt==0){  
  12.   signal(writer);  
  13. }  
  14. signal(mutex);  
  15. }  
  16. }

算法通過共享writer和mutex兩個信號量,來處理同步問題

  1. package mutiple_thread;  
  2.  
  3. import java.util.concurrent.Semaphore;  
  4.  
  5. public class OS_Readerwriter{  
  6.     static Semaphore sem=new Semaphore(1);  
  7.     static Semaphore sem_wrt=new Semaphore(1);  
  8.     static int readercount=0;  
  9.     static String a="hahaha";  
  10.     public static void main(String args[]){  
  11.         class reader implements Runnable{  
  12.             public reader(){  
  13.                   
  14.             }  
  15.             @Override 
  16.             public void run() {  
  17.                 // TODO Auto-generated method stub  
  18.                 try {  
  19.                     sem.acquire();  
  20.                     readercount++;  
  21.                 } catch (InterruptedException e) {  
  22.                     // TODO Auto-generated catch block  
  23.                     e.printStackTrace();  
  24.                 }  
  25.                 if(readercount==1){  
  26.                     try {  
  27.                         sem_wrt.acquire();  
  28.                     } catch (InterruptedException e) {  
  29.                         // TODO Auto-generated catch block  
  30.                         e.printStackTrace();  
  31.                     }  
  32.                 }  
  33.                 sem.release();  
  34.                   
  35.                 System.out.println("Reading "+a);  
  36.                   
  37.                 try {  
  38.                     sem.acquire();  
  39.                 } catch (InterruptedException e) {  
  40.                     // TODO Auto-generated catch block  
  41.                     e.printStackTrace();  
  42.                 }  
  43.                 readercount--;  
  44.                 if(readercount==0){  
  45.                     sem_wrt.release();  
  46.                 }  
  47.                 sem.release();  
  48.             }  
  49.         }  
  50.           
  51.         class writer implements Runnable{  
  52.             public writer(){  
  53.                   
  54.             }  
  55.             @Override 
  56.             public void run() {  
  57.                 // TODO Auto-generated method stub  
  58.                 try {  
  59.                     sem_wrt.acquire();  
  60.                 } catch (InterruptedException e) {  
  61.                     // TODO Auto-generated catch block  
  62.                     e.printStackTrace();  
  63.                 }  
  64.                 a=a+"abc";  
  65.                 System.out.println("Writing "+a);  
  66.                 sem_wrt.release();  
  67.             }  
  68.               
  69.         }  
  70.         for(int i=1;i<=10;i++){  
  71.             new Thread(new writer()).start();  
  72.             new Thread(new reader()).start();  
  73.         }  
  74.           
  75.     }  

2.2 哲學家問題

算法思路:通過對每一只筷子設置信號量,來進行同步判斷。

Java實現代碼如下:

  1. package mutiple_thread;  
  2.  
  3. import java.util.concurrent.Semaphore;  
  4.  
  5. public class OS_Philosopher{  
  6.     static int chop[]=new int [7];  
  7.     static Semaphore []sem=new Semaphore[7];  
  8.       
  9.     public static void main(String args[]) throws InterruptedException{  
  10.         for(int i=0;i<=6;i++){  
  11.             sem[i]=new Semaphore(1);  
  12.         }  
  13.         Thread.sleep(1000);  
  14.         class philosopher implements Runnable{  
  15.             int i;  
  16.             public philosopher(int i){  
  17.                 this.i=i;  
  18.             }  
  19.  
  20.             @Override 
  21.             public void run() {  
  22.                 // TODO Auto-generated method stub  
  23.                 while(true){  
  24.                     try {  
  25.                         synchronized(this){  
  26.                             sem[i].acquire();  
  27.                             sem[(i+1)%5].acquire();  
  28.                         }  
  29.                           
  30.                     } catch (InterruptedException e) {  
  31.                         // TODO Auto-generated catch block  
  32.                         e.printStackTrace();  
  33.                     }  
  34.                     System.out.println("Phi"+i+" is Eating");  
  35.                     //sleep();  
  36.                     try {  
  37.                         Thread.sleep(1);  
  38.                     } catch (InterruptedException e) {  
  39.                         // TODO Auto-generated catch block  
  40.                         e.printStackTrace();  
  41.                     }  
  42.                     sem[i].release();  
  43.                     sem[(i+1)%5].release();  
  44.                     System.out.println("Phi"+i+" is Thinking");  
  45.                     //sleep();  
  46.                     try {  
  47.                         Thread.sleep(1);  
  48.                     } catch (InterruptedException e) {  
  49.                         // TODO Auto-generated catch block  
  50.                         e.printStackTrace();  
  51.                     }  
  52.                 }  
  53.             }  
  54.         }  
  55.         philosopher t1=new philosopher(1);  
  56.         philosopher t2=new philosopher(2);  
  57.         philosopher t3=new philosopher(3);  
  58.         philosopher t4=new philosopher(4);  
  59.         philosopher t5=new philosopher(5);  
  60.         new Thread(t1).start();  
  61.         new Thread(t2).start();  
  62.         new Thread(t3).start();  
  63.         new Thread(t4).start();  
  64.         new Thread(t5).start();  
  65.           
  66.     }  

2.3 理發店問題:

理發店理有一位理發師、一把理發椅和 5 把供等候理發的顧客坐的椅 子。如果沒有顧客,理發師便在理發椅上睡覺。一個顧客到來時,它必須叫 醒理發師。如果理發師正在理發時又有顧客來到,則如果有空椅子可坐,就 坐下來等待,否則就離開。

算法思路如下:采用信號量進行判斷。初始值為1,即是有一個理發師在服務。

實現代碼如下:

  1. package mutiple_thread;  
  2.  
  3. import java.util.concurrent.Semaphore;  
  4.  
  5. public class OS_Barber1{  
  6.     static int cnt = 0;  
  7.     static int MAX = 5;  
  8.     static int busy = 0;  
  9.     static Semaphore sem=new Semaphore(1);  
  10.     public static void main(String args[]) throws InterruptedException{  
  11.         OS_Barber1 bar=new OS_Barber1();  
  12.         for(int i=1;i<=20;i++){  
  13.             new Thread(new Bar1(bar,i)).start();  
  14.             Thread.sleep((int) (400 - Math.random() * 300));  
  15.         }  
  16.     }  
  17.     public synchronized boolean isFull() {  
  18.         if (cnt == MAX) {  
  19.             return true;  
  20.         }  
  21.         return false;  
  22.     }  
  23.  
  24.     public synchronized boolean isEmpty() {  
  25.         if (cnt == 0) {  
  26.             return true;  
  27.         }  
  28.         return false;  
  29.     }  
  30.  
  31.     public synchronized boolean isBusy() {  
  32.         if (busy == 1) {  
  33.             return true;  
  34.         }  
  35.         return false;  
  36.     }  
  37.       
  38.     public  void Gobar(int index) throws InterruptedException{  
  39.           
  40.           
  41.         System.out.println("Con"+index+" is coming");  
  42.         cnt++;  
  43.         //判斷是否滿  
  44.         if(isFull()){  
  45.             System.out.println("Is full,"+"Con"+index+" is leaving");  
  46.             cnt--;  
  47.         }else{  
  48.             if(busy==1){  
  49.                 System.out.println("Con"+index+" is waitting");  
  50.             }  
  51.             //sem.acquire();  
  52.             synchronized (this){  
  53.                 while(busy==1){  
  54.                     //若有人在理發,則等待  
  55.                     wait();  
  56.                 }  
  57.             }  
  58.               
  59.             if(cnt==1){  
  60.                 System.out.println("Con"+index+" is wake");  
  61.             }  
  62.             busy=1;  
  63.             System.out.println("Con"+index+" is Serving");  
  64.             Thread.sleep(1000);  
  65.             System.out.println("Con"+index+" is leaving");  
  66.             cnt--;  
  67.             //sem.release();  
  68.             synchronized (this){  
  69.                 busy=0;  
  70.                 //喚醒  
  71.                 notify();  
  72.             }  
  73.             if(cnt==0){  
  74.                 System.out.println("Bar is sleep");  
  75.             }  
  76.         }  
  77.     }  
  78. }  
  79. class Bar1 implements Runnable {  
  80.     OS_Barber1 ob;  
  81.     int index;  
  82.     public Bar1(OS_Barber1 ob,int i) {  
  83.         this.ob = ob;  
  84.         index=i;  
  85.     }  
  86.  
  87.     @Override 
  88.     public void run() {  
  89.         // TODO Auto-generated method stub  
  90.         try {  
  91.             ob.Gobar(index);  
  92.         } catch (InterruptedException e) {  
  93.             // TODO Auto-generated catch block  
  94.             e.printStackTrace();  
  95.         }  
  96.     }  
  97.  

在算法中我使用了wait(),notify()來實現,也可以使用信號量來實現,注釋部分就是使用信號量的實現。

在實現過程中,我發現了一些問題,也就是下面要討論的wait() 和notify() 和notifyAll()

3、 wait() ,notify() 和notifyAll()

synchronized 方法控制對類成員變量的訪問:每個類實例對應一把鎖,每個 synchronized 方法都必須獲得調用該方法的類實例的鎖方能執行,否則所屬線程阻塞,方法一旦執行,就獨占該鎖,直到從該方法返回時才將鎖釋放,此后被阻塞的線程方能獲得該鎖,重新進入可執行狀態。

wait()/notify():調用任意對象的 wait() 方法導致線程阻塞,并且該對象上的鎖被釋放。而調用 任意對象的notify()方法則導致因調用該對象的 wait() 方法而阻塞的線程中隨機選擇的一個解除阻塞(但要等到獲得鎖后才真正可執行)。

synchronized和wait()、notify()的關系

1.有synchronized的地方不一定有wait,notify

2.有wait,notify的地方必有synchronized.這是因為wait和notify不是屬于線程類,而是每一個對象都具有的方法,而且,這兩個方法都和對象鎖有關,有鎖的地方,必有synchronized。

另外,請注意一點:如果要把notify和wait方法放在一起用的話,必須先調用notify后調用wait,因為如果調用完wait,該線程就已經不是current thread了。

注:調用wait()方法前的判斷***用while,而不用if;while可以實現被wakeup后thread再次作條件判斷;而if則只能判斷一次;

線程的四種狀態

  1. 新狀態:線程已被創建但尚未執行(start() 尚未被調用)。
  2. 可執行狀態:線程可以執行,雖然不一定正在執行。CPU 時間隨時可能被分配給該線程,從而使得它執行。
  3. 死亡狀態:正常情況下 run() 返回使得線程死亡。調用 stop()或 destroy() 亦有同樣效果,但是不被推薦,前者會產生異常,后者是強制終止,不會釋放鎖。
  4. 阻塞狀態:線程不會被分配 CPU 時間,無法執行。

首先,前面敘述的所有方法都隸屬于 Thread 類,但是這一對 (wait()/notify()) 卻直接隸屬于 Object 類,也就是說,所有對象都擁有這一對方法。初看起來這十分不可思議,但是實際上卻是很自然的,因為這一對方法阻塞時要釋放占用的鎖,而鎖是任何對象都具有的,調用任意對象的 wait() 方法導致線程阻塞,并且該對象上的鎖被釋放。而調用 任意對象的notify()方法則導致因調用該對象的 wait() 方法而阻塞的線程中隨機選擇的一個解除阻塞(但要等到獲得鎖后才真正可執行)。

其次,前面敘述的所有方法都可在任何位置調用,但是這一對方法卻必須在 synchronized 方法或塊中調用,理由也很簡單,只有在synchronized 方法或塊中當前線程才占有鎖,才有鎖可以釋放。

同樣的道理,調用這一對方法的對象上的鎖必須為當前線程所擁有,這樣才有鎖可以釋放。因此,這一對方法調用必須放置在這樣的synchronized 方法或塊中,該方法或塊的上鎖對象就是調用這一對方法的對象。若不滿足這一條件,則程序雖然仍能編譯,但在運行時會出現IllegalMonitorStateException 異常。

wait() 和 notify() 方法的上述特性決定了它們經常和synchronized 方法或塊一起使用,將它們和操作系統的進程間通信機制作一個比較就會發現它們的相似性:synchronized方法或塊提供了類似于操作系統原語的功能,它們的執行不會受到多線程機制的干擾,而這一對方法則相當于 block 和wakeup 原語(這一對方法均聲明為 synchronized)。它們的結合使得我們可以實現操作系統上一系列精妙的進程間通信的算法(如信號量算法),并用于解決各種復雜的線程間通信問題。關于

wait() 和 notify() 方法***再說明兩點:

***:調用 notify() 方法導致解除阻塞的線程是從因調用該對象的 wait() 方法而阻塞的線程中隨機選取的,我們無法預料哪一個線程將會被選擇,所以編程時要特別小心,避免因這種不確定性而產生問題。

第二:除了 notify(),還有一個方法 notifyAll() 也可起到類似作用,唯一的區別在于,調用 notifyAll() 方法將把因調用該對象的wait() 方法而阻塞的所有線程一次性全部解除阻塞。當然,只有獲得鎖的那一個線程才能進入可執行狀態。

談到阻塞,就不能不談一談死鎖,略一分析就能發現,suspend() 方法和不指定超時期限的 wait() 方法的調用都可能產生死鎖。遺憾的是,Java 并不在語言級別上支持死鎖的避免,我們在編程中必須小心地避免死鎖。

以上我們對 Java 中實現線程阻塞的各種方法作了一番分析,我們重點分析了 wait() 和 notify()方法,因為它們的功能***大,使用也最靈活,但是這也導致了它們的效率較低,較容易出錯。實際使用中我們應該靈活使用各種方法,以便更好地達到我們的目的。

原文鏈接:http://blog.csdn.net/rommel1/article/details/7322327

【編輯推薦】

  1. Java web應用中的常見字符編碼問題的解決方法
  2. Java中String.format的用法
  3. 如何在Oracle中使用Java存儲過程(詳解)
  4. 郵件功能開發:JavaMail
  5. 關于讀寫鎖算法的Java實現及思考
責任編輯:林師授 來源: rommel1的博客
相關推薦

2017-09-19 14:53:37

Java并發編程并發代碼設計

2020-11-16 08:11:32

ReentrantLo

2025-02-17 02:00:00

Monitor機制代碼

2019-11-07 09:20:29

Java線程操作系統

2021-03-10 15:59:39

JavaSynchronize并發編程

2020-11-30 16:01:03

Semaphore

2020-12-09 08:21:47

編程Exchanger工具

2020-12-16 10:54:52

編程ForkJoin框架

2024-08-08 08:19:03

2020-11-13 08:42:24

Synchronize

2020-12-11 07:32:45

編程ThreadLocalJava

2020-12-04 19:28:53

CountDownLaPhaserCyclicBarri

2020-12-03 11:15:21

CyclicBarri

2013-08-07 10:46:07

Java并發編程

2020-07-06 08:03:32

Java悲觀鎖樂觀鎖

2012-03-01 20:32:29

iOS

2020-12-07 09:40:19

Future&Futu編程Java

2017-01-10 13:39:57

Python線程池進程池

2024-11-27 09:26:29

2025-04-25 08:00:00

volatileJava編程
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美亚洲视频 | 久久久久国产 | 国产小u女发育末成年 | 狠狠干美女 | 欧洲免费毛片 | 国产精品国产a级 | 欧美成年人 | 爱草在线 | 一级毛片色一级 | 亚洲欧美日韩一区 | 精品久久久久久久久久久久久久久久久 | 日韩欧美在线视频 | 91视频观看| 中文字幕在线观看视频一区 | 97精品国产97久久久久久免费 | 美女黄18岁以下禁止观看 | 亚洲444kkkk在线观看最新 | 免费在线观看一区二区 | 成人午夜精品 | 精品一区在线免费观看 | 7777在线| 欧美区日韩区 | 精品国产伦一区二区三区观看体验 | 欧美夜夜| 91网站视频在线观看 | 91精品在线播放 | 西西裸体做爰视频 | 久久成人精品视频 | 日韩免费视频一区二区 | 91精品久久久久久久久 | 日韩一区二区在线视频 | 成人av高清在线观看 | 日本一区二区不卡视频 | 亚洲欧美在线观看 | 日本人和亚洲人zjzjhd | 黄色一级免费 | www.中文字幕.com | 亚洲福利片 | 欧美日韩成人 | 午夜免费视频观看 | 亚洲高清网 |