多執行緒基礎4 同步與通訊

2021-08-28 06:35:13 字數 2575 閱讀 5412

1.什麼情況下需要同步 當多執行緒併發執行同一**時 希望某一段**執行的過程中cpu不要切換到其他執行緒工作. 這時就需要同步. 

2.同步**塊 使用synchronized關鍵字加上乙個鎖物件來定義一段**, 這就叫同步**塊 多個同步**塊如果使用相同的鎖物件, 那麼他們就是同步的

}//非靜態同步函式的鎖是:this (非靜態方法已建立例項化物件後呼叫的)

public synchronized void print2()

// 靜態的同步函式的鎖是:位元組碼物件.class (靜態是初始化時形成的所以 是位元組碼物件)

public static synchronized void print3()

}

public class demo1_notify  catch (interruptedexception e) }}

}.start();

new thread() catch (interruptedexception e) }}

}.start();

}}//等待喚醒機制

class printer

system.out.print("方法一");

system.out.print("\r\n");

flag = 2;

this.notify();                //隨機喚醒單個等待的執行緒}}

public void print2() throws interruptedexception

system.out.print("方法2");

system.out.print("\r\n");

flag = 1;

this.notify();}}

}

多個執行緒通訊的問題 * notify()方法是隨機喚醒乙個執行緒 * notifyall()方法是喚醒所有執行緒 * jdk5之前無法喚醒指定的乙個執行緒 * 如果多個執行緒之間通訊, 需要使用notifyall()通知所有執行緒, 用while來反覆判斷條件

public class demo2_notifyall  catch (interruptedexception e) }}

}.start();

new thread() catch (interruptedexception e) }}

}.start();

new thread() catch (interruptedexception e) }}

}.start();}}

1,在同步**塊中,用哪個物件鎖,就用哪個物件呼叫wait方法

2,為什麼wait方法和notify方法定義在object這類中?

因為鎖物件可以是任意物件,object是所有的類的基類,所以wait方法和notify方法需要定義在object這個類中

3,sleep方法和wait方法的區別?

a,sleep方法必須傳入引數,引數就是時間,時間到了自動醒來wait方法可以傳入引數也可以不傳入引數,傳入引數就是在引數的時間結束後等待,不傳入引數就是直接等待

b,sleep方法在同步函式或同步**塊中,不釋放鎖,睡著了也抱著鎖睡wait方法在同步函式或者同步**塊中,釋放鎖

class printer2 

system.out.print("方法一");

system.out.print("\r\n");

flag = 2;

//隨機喚醒單個等待的執行緒

this.notifyall();}}

public void print2() throws interruptedexception

system.out.print("方法2");

system.out.print("\r\n");

flag = 3;

this.notifyall();}}

public void print3() throws interruptedexception

system.out.print("方法三");

system.out.print("\r\n");

flag = 1;

this.notifyall();}}

}

消費者與生產者

//消費者

synchronized(物件)

//生產者

synchronized(物件)

執行緒間的通訊還可以使用 管道輸入/輸出流

public class piped 

} finally

}static class print implements runnable

public void run()

} catch (ioexception ex) }}

}

Java多執行緒 執行緒的同步與通訊

一 執行緒的同步class window2 implements runnable public class testwindow2 方式二 同步方法 將操作共享資料的方法宣告為synchronized,即此方法為同步方法,能夠保證當其中乙個執行緒執行 此方法時,其他執行緒在外等待直至此執行緒執行完...

4 執行緒同步通訊

子執行緒迴圈10次,接著主線程迴圈100次,接著又回到子執行緒迴圈10次,接著再回到主線程又迴圈100,如此迴圈50,請寫出程式。package cn.itcast.thread public class traditionalcomuication start new thread new run...

程序間通訊與多執行緒同步

常見的程序間通訊方式包括 管道 pipe 共享記憶體 sharedmemory 訊息佇列 messagequeue 訊號量 semaphore socket 套接字 常見的多執行緒同步方式主有 是臨界區 critical section 互斥鎖 mutex 訊號量 semaphore 事件 even...