簡體   English   中英

如何確保 Java 線程按特定順序運行

[英]How to ensure Java threads run in a particular order

給定三個線程,1-3,打印一個字母 AC,我如何保證輸出順序?

我希望線程的輸出為“ABCABCABC”

線程獨立運行,因此除非您特別努力同步線程,否則您永遠不會獲得此類輸出。 預計 3 個獨立運行的線程會打印“隨機”輸出,因為由操作系統來調度線程。

這可能不是線程應該做的,但是可以通過簡單地使用 join 來實現(它要求開始ING線程等待開始ED線程的完成。

class A implements Runnable {

@Override
public void run() {
    try {
        Thread.sleep(12);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("ClassA : A");
}

}

class B implements Runnable {

@Override
public void run() {
    try {
        Thread.sleep(12);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("ClassB : B");
}

}

class C implements Runnable {

@Override
public void run() {
    try {
        Thread.sleep(12);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("ClassC : C");
}

}

public class OrderedThreadApp {
public static void main(String[] args) {

    Thread a = new Thread(new A());
    Thread b = new Thread(new B());
    Thread c = new Thread(new C());

    a.start();
    try {
        a.join();
        b.start();
        b.join();
        c.start();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

我的解決方案在這里: https : //gist.github.com/sinujohn/5fa717dfff680634c6b0c2a7eca108ac可以修改來實現這一點。 這個想法是創建一個保存狀態的對象並在所有線程之間共享該對象。 只有一個同步塊可以訪問共享狀態對象。

public class Main {

    public static void main(String[] args) throws InterruptedException {
        MyState state = new MyState();

        final Thread t1 = new Thread(new MyRunnable(10, 'A', state));
        final Thread t2 = new Thread(new MyRunnable(10, 'B', state));
        final Thread t3 = new Thread(new MyRunnable(10, 'C', state));
        t1.start();
        t2.start();
        t3.start();
    }
}

class MyState {
    private char state = 'A';

    public char getState() {
        return state;
    }

    public void incrState() {
        switch(state) {
        case 'A':
            state = 'B';
            return;
        case 'B':
            state = 'C';
            return;
        default:
            state = 'A';
        }
    }
}

class MyRunnable implements Runnable {

    private final int max;
    private final char value;
    private final MyState state;

    MyRunnable(int max, char value, MyState state) {
        this.max = max;
        this.value = value;
        this.state = state;
    }

    @Override
    public void run() {
        int count = 0;
        while(count < max) {
            synchronized (this.state) {
                if (this.state.getState() == this.value) {
                    System.out.print(value);
                    count++;
                    this.state.incrState();
                }
            }
        }
    }
}

檢查CyclicBarrier ,這可能對您有所幫助。

您可以通過組合CountDownLatchCyclicBarrier來實現這一點。 這是示例代碼:

    package org.orange.didxga;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class ThreadExecutionOrder {

    private CountDownLatch countDownLatch = new CountDownLatch(2);
    private CountDownLatch countDownLatch1 = new CountDownLatch(1);
    private CyclicBarrier barrier;
    private final Object monitor = new Object();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new ThreadExecutionOrder().test();
    }

    public void test() {
        Runnable t1 = new Runnable() {

            @Override
            public void run() {
                System.out.print("A");
                countDownLatch1.countDown();
                countDownLatch.countDown();
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }

        };
        Runnable t2 = new Runnable() {

            @Override
            public void run() {
                try {
                    countDownLatch1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("B");
                countDownLatch.countDown();
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }

        };
        Runnable t3 = new Runnable() {

            @Override
            public void run() {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("C");
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }

        };
        for(int i=0; i<3; i++) {
            barrier = new CyclicBarrier(3, new Runnable()  {
                @Override
                public void run() {
                    synchronized (monitor) {
                        countDownLatch = new CountDownLatch(2);
                        countDownLatch1 = new CountDownLatch(1);
                        monitor.notify();
                    }
                }

            });
            new Thread(t1).start();
            new Thread(t2).start();
            new Thread(t3).start();
            synchronized (monitor) {
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

您可以使用 wait 和 notify 進行線程間通信。 我在這里使用 turn int 變量在線程之間發送信號。

public class ThreadInterleaving{
    public static void main(String[] args){

    MyThread h = new MyThread();

    Thread t1 = new Thread(h);
    Thread t2 = new Thread(h);
    Thread t3 = new Thread(h);

    t1.start();
    t2.start();
    t3.start();

    }
}

class MyThread implements Runnable{
    public static int turn;

    @Override
    public void run(){
        for(int i =0;i<3;i++){
            synchronized(this){
                if(turn == 0){
                    System.out.println("Thread1");
                    turn =1 ;
                    notify();
                }else{
                    try{
                        wait();
                    }catch(InterruptedException ie){

                    }
                }

                if(turn == 1){
                    System.out.println("Thread2");
                    turn = 2;
                    notify();
                }else{
                    try{
                        wait();
                    }catch(InterruptedException ie){

                    }
                }

                if(turn == 2){
                    System.out.println("Thread3");
                    System.out.println("*********");
                    turn = 0;
                    notify();
                }else{
                    try{
                        wait();
                    }catch(InterruptedException ie){        

                    }
                }
            }
        }
    }
}

/*Output
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
Thread1
Thread2
Thread3
*********
*/
public class RunningThreadSequentially {
    //Runnable task for each thread
    private static class Task implements Runnable {
        public static int counter=0;

        @Override
        public void run() {
            try {
                synchronized(this) {
                    Thread.sleep(500);
                    System.out.println(Thread.currentThread().getName() + " is completed--" + counter ++);             
                }
            } catch (Exception ex) {
            } 
        }
    }

    public static void main(String args[]) throws InterruptedException {
        while(true) {
            Thread t1 = new Thread(new Task(), "Thread 1");
            Thread t2 = new Thread(new Task(), "Thread 2");
            Thread t3 = new Thread(new Task(), "Thread 3");
            Thread t4 = new Thread(new Task(), "Thread 4");
            Thread t5 = new Thread(new Task(), "Thread 5");
            Thread t6 = new Thread(new Task(), "Thread 6");

            t1.start();
            t1.join();
            t2.start();
            t2.join();
            t3.start(); 
            t3.join(); 
            t4.start(); 
            t4.join(); 
            t5.start();
            t5.join(); 
            t6.start(); 
            t6.join();
        }
    }
}
public class ThreadOrderTest {

int status = 1;

public static void main(String[] args) {
    ThreadOrderTest threadOrderTest = new ThreadOrderTest();
    A a = new A(threadOrderTest);
    B b = new B(threadOrderTest);
    C c = new C(threadOrderTest);
    a.start();
    b.start();
    c.start();
}
}

class A extends Thread {

ThreadOrderTest threadOrderTest;

A(ThreadOrderTest threadOrderTest) {
    this.threadOrderTest = threadOrderTest;
}

@Override
public void run() {
    try {
        synchronized (threadOrderTest) {
            for (int i = 0; i < 10; i++) {
                while (threadOrderTest.status != 1) {
                    threadOrderTest.wait();
                }
                System.out.print("A ");
                threadOrderTest.status = 2;
                threadOrderTest.notifyAll();
            }
        }
    } catch (Exception e) {
        System.out.println("Exception 1 :" + e.getMessage());
    }
}
}

class B extends Thread {

ThreadOrderTest threadOrderTest;

B(ThreadOrderTest threadOrderTest) {
    this.threadOrderTest = threadOrderTest;
}

@Override
public void run() {
    try {
        synchronized (threadOrderTest) {
            for (int i = 0; i < 10; i++) {
                while (threadOrderTest.status != 2) {
                    threadOrderTest.wait();
                }
                System.out.print("B ");
                threadOrderTest.status = 3;
                threadOrderTest.notifyAll();
            }
        }
    } catch (Exception e) {
        System.out.println("Exception 2 :" + e.getMessage());
    }
}
}

class C extends Thread {

ThreadOrderTest threadOrderTest;

C(ThreadOrderTest threadOrderTest) {
    this.threadOrderTest = threadOrderTest;
}

@Override
public void run() {
    try {
        synchronized (threadOrderTest) {
            for (int i = 0; i < 10; i++) {
                while (threadOrderTest.status != 3) {
                    threadOrderTest.wait();
                }
                System.out.println("C ");
                threadOrderTest.status = 1;
                threadOrderTest.notifyAll();
            }
        }
    } catch (Exception e) {
        System.out.println("Exception 3 :" + e.getMessage());
    }
}
}

執行者服務

一個 Executor 提供管理終止的方法和可以生成 Future 以跟蹤一個或多個異步任務的進度的方法。

ExecutorService 可以關閉,這將導致它拒絕新任務。 提供了兩種不同的方法來關閉 ExecutorService。 shutdown() 方法將允許先前提交的任務在終止之前執行,而 shutdownNow() 方法阻止等待任務開始並嘗試停止當前正在執行的任務。 終止時,執行器沒有正在執行的任務,沒有等待執行的任務,也沒有新的任務可以提交。 應關閉未使用的 ExecutorService 以允許回收其資源。

方法 submit 通過創建和返回可用於取消執行和/或等待完成的 Future 來擴展基本方法 Executor.execute(java.lang.Runnable)。 方法 invokeAny 和 invokeAll 執行最常用的批量執行形式,執行一組任務,然后等待至少一個或全部完成。 (類 ExecutorCompletionService 可用於編寫這些方法的自定義變體。)

Executors 類為此包中提供的執行程序服務提供了工廠方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM