如何确保Java线程以特定顺序运行

时间:2013-04-14 09:17:13

标签: java

给出三个线程,1-3,打印一个字母,A-C,我该如何保证输出顺序?

我希望线程的输出为“ABCABCABC”

8 个答案:

答案 0 :(得分:4)

线程独立运行,因此除非您特别努力同步线程,否则永远不会获得此类输出。预期独立运行的3个线程将打印“随机”输出,因为它可以由OS来调度线程。

答案 1 :(得分:0)

检查CyclicBarrier,这可能会对您有所帮助。

答案 2 :(得分:0)

您可以通过合并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();
                }
            }
        }
    }

}

答案 3 :(得分:0)

您可以使用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
*********
*/

答案 4 :(得分:0)

我在这里的解决方案: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();
                }
            }
        }
    }
}

答案 5 :(得分:0)

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

答案 6 :(得分:-1)

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

答案 7 :(得分:-2)

ExecutorService

  

Executor,提供管理终止和方法的方法   这可以产生一个跟踪一个或多个进度的Future   异步任务。

     

可以关闭ExecutorService,这将导致它拒绝新的   任务。提供了两种不同的方法来关闭   ExecutorService的。 shutdown()方法将允许先前提交   在终止之前执行的任务,而shutdownNow()方法   阻止等待任务启动并尝试暂停   执行任务。终止后,执行者没有主动执行任务   执行,没有等待执行的任务,也没有新的任务   提交。应该关闭一个未使用的ExecutorService以允许   回收其资源。

     

方法提交扩展基本方法Executor.execute(java.lang.Runnable)   通过创建和返回可用于取消的Future   执行和/或等待完成。方法invokeAny和invokeAll   执行最常用的批量执行形式,执行a   收集任务,然后等待至少一个或全部   完成。 (可以使用ExecutorCompletionService类编写   这些方法的定制变体。)

     

Executors类为执行程序服务提供工厂方法   在这个包中提供。