Java中多个线程按顺序执行

 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();
    }
}

引用:http://netjavaliu.blog.sohu.com/143449586.html

你可能感兴趣的:(java)