yield()表示執行緒謙讓,將釋放cpu;
原子基本物件類可以優化執行緒,基本型別的加減操作可能出現併發,需要加鎖;這時使用automic類;
lock() ;unlock()函式與syncnozied,都是同步**塊,不同在於,lock()同步多個函式操作;
threadlocal 變數是執行緒複製建立的,獨有的,不會被其他執行緒修改,最好做出static 類型別;
static threadlocalthreadint;
suspend()和resume()被廢止,可能導致死鎖;
stop()方法廢止,因為不釋放鎖;
thread.interrupt()終止任務,一般是阻塞的執行緒;會丟擲異常;thread.interrupted()不會丟擲異常;
任務之間的協作。condition類的await();signal()和signalall()函式;object類的wait(),notify()
無界佇列listedblockingqueue,同步佇列blockingqueue,有界佇列arrayblockingqueue;生產者和消費者佇列;
未完簡單的消費者,生產者執行緒
public class sig
}class producer implements runnable
@override
public void run()
else}}
}catch (interruptedexception e)
}private int produce()
}class consumer implements runnable
@override
public void run()
else}}
catch (interruptedexception e)
}private void consume(integer n)
}簡單的lock訊號量鎖,控制函式的執行順序
public class threeconditioncommunication
}}).start();
//子執行緒3
new thread(
new runnable()
}}).start();
//主線程
for (int i = 1; i <= 5; i++)
}/**
* 建立乙個靜態的類
* 將核心的業務邏輯的方法放在這裡
* 體現了高內聚的特點
* @author huang.jf
*/static class core catch (interruptedexception e)
}//執行緒2執行
system.out.println("this is sub2 thread...");
hasout = 3;
condition1.signalall();//喚醒執行緒3
}finally
}//執行緒3 迴圈輸出20次
public void submethod3(int j) catch (interruptedexception e)
}//執行緒3執行
system.out.println("this is sub3 thread...");
hasout = 1;
condition1.signalall();//喚醒執行緒1(主線程)
}finally
}//主線程呼叫迴圈輸出一百次
public void mainmethod(int j) catch (interruptedexception e)
}//執行主線程
system.out.println("this is main thread...");
hasout = 2;
condition1.signalall();//喚醒執行緒2
}finally}}
}
執行緒學習9 Mutex類
互斥 在作業系統中,許多執行緒常常需要共享資源,而這些資源往往要求一次只能為乙個執行緒服務 排他性 這種排他性地使用共享資源稱為執行緒間的互斥。執行緒互斥實質上也是同步,可以看做一種特殊的執行緒同步。mutex類 執行緒的互斥常用mutex類實現,利用它可以對資源進行獨占性訪問。與monitor類相...
執行緒學習2 Thread類
thread 類 使用thread類可以建立和控制線程,thread類有如下方法 start 啟動執行緒 sleep int 靜態方法,暫停當前執行緒指定的毫秒數 abort 通常使用該方法來終止乙個執行緒 suspend 該方法並不終止未完成的執行緒,它僅僅掛起執行緒,以後還可恢復 resume ...
多執行緒學習 ThreadLocal類的使用
類threadlocal主要解決的就是每個執行緒繫結自己的值,可以將threadlocal模擬喻成全域性存放資料的盒子,盒子裡可以儲存每個執行緒的私有資料。使執行緒變數具有隔離性。設定兩個執行緒threada和threadb,每個執行緒都分別為用threadlocal設定值和取值。public cl...