Java Thread隊列詳細代碼的介紹
作者:佚名
Java Thread隊列一直是很多程序員頭疼的事情,其實不要太著急。下面我們就看看如何才能更好的使用相關的Java Thread隊列。
Java Thread隊列一直是我們需要掌握的代碼。下面我們就基本思想:建立了一個隊列,為每一個Java Thread隊列保存了一個對象鎖,保證按順序執行。線程啟動的時候,使隨機的,但是執行代碼是按順序的。
- import java.util.LinkedList;
- import java.util.Queue;
- public class ThreadTest {
- private static Queue qThread=new LinkedList();//線程同步對象隊列
- public static synchronized void putObject(Object t){
- qThread.offer(t);
- }
- public static synchronized Object getObject(){
- return qThread.poll();
- }
- public static void waitThread(Object t) throws InterruptedException{
- synchronized(t){
- t.wait();
- }
- }
- public static void notifyThread(){
- Object obj=ThreadTest.getObject();
- synchronized(obj){
- obj.notify();
- }
- }
- public static void main(String[] args) throws InterruptedException {
- int i = 0;
- boolean isFirst=true;
- while (i < 10) {
- Object obj=new Object();
- if(i>0){
- isFirst=false;
- ThreadTest.putObject(obj);
- }
- Thread t2 = new Thread2(isFirst,obj);
- Object obj2=new Object();
- ThreadTest.putObject(obj2);
- Thread t3 = new Thread3(obj2);
- t2.start();
- t3.start();
- i++;
- }
- }
- }
- /**
- * 線程2
- *
- * @author Harry.WANG
- *
- */
- class Thread2 extends Thread {
- private boolean isFirst=false;
- private Object obj;
- public Thread2(boolean f,Object obj){
- this.isFirst=f;
- this.obj=obj;
- }
- @Override
- public void run() {
- if(!this.isFirst){
- System.out.println(this.getName()+"等待...");
- try{
- ThreadTest.waitThread(obj);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- System.out.println("啟動"+this.getName()+"...");
- try {
- sleep(3000);//等待3秒,為了測試
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("停止"+this.getName()+"...");
- ThreadTest.notifyThread();
- }
- }
- class Thread3 extends Thread {
- private Object obj;
- public Thread3(Object obj){
- this.obj=obj;
- }
- @Override
- public void run() {
- System.out.println(this.getName()+"等待...");
- try{
- ThreadTest.waitThread(obj);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println("啟動"+this.getName()+"...");
- try {
- sleep(3000);//等待3秒,為了測試
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("停止"+this.getName()+"...");
- ThreadTest.notifyThread();
- }
- }
以上就是對Java Thread隊列的詳細介紹。希望大家有所幫助。
【編輯推薦】
責任編輯:張浩
來源:
互聯網