Ordering threads to run in the order they were created/started

前端 未结 10 1186
礼貌的吻别
礼貌的吻别 2020-11-30 06:15

How can i order threads in the order they were instantiated.e.g. how can i make the below program print the numbers 1...10 in order.

public class ThreadOrder         


        
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 06:45

    Control of thread execution order may be implemented quite easily with the semaphores. The code attached is based on the ideas presented in Schildt's book on Java (The complete reference....). // Based on the ideas presented in: // Schildt H.: Java.The.Complete.Reference.9th.Edition.

    import java.util.concurrent.Semaphore;
    
    class Manager {
        int n;
    // Initially red on semaphores 2&3; green semaphore 1.
        static Semaphore SemFirst = new Semaphore(1);
        static Semaphore SemSecond = new Semaphore(0);
        static Semaphore SemThird = new Semaphore(0);
    
    void firstAction () {
        try {
            SemFirst.acquire();
        } catch(InterruptedException e) {
            System.out.println("Exception InterruptedException catched");
        }
        System.out.println("First: " );
        System.out.println("-----> 111");
        SemSecond.release();
    }
    void secondAction() {
        try{
            SemSecond.acquire();
        } catch(InterruptedException e) {
            System.out.println("Exception InterruptedException catched");
        }
        System.out.println("Second: ");
        System.out.println("-----> 222");
        SemThird.release();
    }
    void thirdAction() {
        try{
            SemThird.acquire();
        } catch(InterruptedException e) {
            System.out.println("Exception InterruptedException catched");
        }
        System.out.println("Third: ");
        System.out.println("-----> 333");
        SemFirst.release();
    }
    }
    
    class Thread1 implements Runnable {
        Manager q;
    
        Thread1(Manager q) {
        this.q = q;
        new Thread(this, "Thread1").start();
    }
    
    public void run() {
        q.firstAction();
    }
    }
    
    class Thread2 implements Runnable {
        Manager q;
    
        Thread2(Manager q) {
        this.q = q;
        new Thread(this, "Thread2").start();
    }
    
    public void run() {
        q.secondAction();
    }
    }
    
    class Thread3 implements Runnable {
        Manager q;
    
        Thread3(Manager q) {
        this.q = q;
        new Thread(this, "Thread3").start();
    }
    
    public void run() {
        q.thirdAction();
    }
    }
    
    class ThreadOrder {
        public static void main(String args[]) {
        Manager q = new Manager();
        new Thread3(q);
        new Thread2(q);
        new Thread1(q);
        }
    }
    

提交回复
热议问题