면접 관:ABC 세 스 레 드 는 어떻게 순서 집행 을 보장 합 니까?

14974 단어 다 중 스 레 드
CountDownlatch 사용 하기

public class ThreadOderRun {

    public static void main(String[] args) {
        ThreadOderRun threadOderRun = new ThreadOderRun();
        CountDownLatch l1 = new CountDownLatch(0);
        CountDownLatch l2 = new CountDownLatch(1);
        CountDownLatch l3 = new CountDownLatch(1);
        Thread work1 = new Thread(threadOderRun.new Work(l1, l2, "1"));
        Thread work2 = new Thread(threadOderRun.new Work(l2, l3, "2"));
        Thread work3 = new Thread(threadOderRun.new Work(l3, l3, "3"));
        work1.start();
        work2.start();
        work3.start();
    }


    class Work implements Runnable {
        CountDownLatch c1;
        CountDownLatch c2;
        String msg;

        public Work(CountDownLatch c1, CountDownLatch c2, String msg) {
            this.c1 = c1;
            this.msg = msg;
            this.c2=c2;
        }

        public void run() {
            try {
                c1.await();
                System.out.println(msg);
                c2.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

Atom 원자 류 AtomicInteger 사용 하기

public class ThreadOrderRun2 {

    private AtomicInteger val = new AtomicInteger(1);

    public static void main(String[] args) {
        ThreadOrderRun2 threadOrderRun2 = new ThreadOrderRun2();
        Thread work1 = new Thread(threadOrderRun2.new Work("1", 1));
        Thread work2 = new Thread(threadOrderRun2.new Work("2", 2));
        Thread work3 = new Thread(threadOrderRun2.new Work("3", 3));
        work1.start();
        work2.start();
        work3.start();
    }


    class Work implements Runnable {
        private String msg;
        private int order;

        public Work(String msg, Integer order) {
            this.msg = msg;
            this.order = order;
        }

        public void run() {
            while (true) {
                try {
                    Thread.sleep(100);
                    if (val.get() == order) {
                        System.out.println(msg);
                        val.incrementAndGet();
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

좋은 웹페이지 즐겨찾기