Java Thread隊列一直是我們需要掌握的代碼下面我們就基本思想建立了一個隊列為每一個Java Thread隊列保存了一個對象鎖保證按順序執行線程啟動的時候使隨機的但是執行代碼是按順序的
import javautilLinkedList;
import javautilQueue;
public class ThreadTest {
private static Queue qThread=new LinkedList();//線程同步對象隊列
public static synchronized void putObject(Object t){
qThreadoffer(t);
}
public static synchronized Object getObject(){
return qThreadpoll();
}
public static void waitThread(Object t) throws InterruptedException{
synchronized(t){
twait();
}
}
public static void notifyThread(){
Object obj=ThreadTestgetObject();
synchronized(obj){
objnotify();
}
}
public static void main(String[] args) throws InterruptedException {
int i = ;
boolean isFirst=true;
while (i < ) {
Object obj=new Object();
if(i>){
isFirst=false;
ThreadTestputObject(obj);
}
Thread t = new Thread(isFirstobj);
Object obj=new Object();
ThreadTestputObject(obj);
Thread t = new Thread(obj);
tstart();
tstart();
i++;
}
}
}
/**
* 線程
*
* @author HarryWANG
*
*/
class Thread extends Thread {
private boolean isFirst=false;
private Object obj;
public Thread(boolean fObject obj){
thisisFirst=f;
thisobj=obj;
}
@Override
public void run() {
if(!thisisFirst){
Systemoutprintln(thisgetName()+等待);
try{
ThreadTestwaitThread(obj);
}catch(InterruptedException e){
eprintStackTrace();
}
}
Systemoutprintln(啟動+thisgetName()+);
try {
sleep();//等待秒為了測試
} catch (InterruptedException e) {
eprintStackTrace();
}
Systemoutprintln(停止+thisgetName()+);
ThreadTestnotifyThread();
}
}
class Thread extends Thread {
private Object obj;
public Thread(Object obj){
thisobj=obj;
}
@Override
public void run() {
Systemoutprintln(thisgetName()+等待);
try{
ThreadTestwaitThread(obj);
}catch(InterruptedException e){
eprintStackTrace();
}
Systemoutprintln(啟動+thisgetName()+);
try {
sleep();//等待秒為了測試
} catch (InterruptedException e) {
eprintStackTrace();
}
Systemoutprintln(停止+thisgetName()+);
ThreadTestnotifyThread();
}
}
以上就是對Java Thread隊列的詳細介紹希望大家有所幫助
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27018.html