如何知道哪个线程首先从两个线程中完成执行 [英] How to know which thread completes execution first out of two threads

查看:119
本文介绍了如何知道哪个线程首先从两个线程中完成执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程A和B.如果A首先完成,那么我必须执行function1 else如果B先完成,我需要执行函数2.我知道这两个线程中哪一个先完成了执行? / p>

I have two threads A and B. If A completes first, then I have to execute function1 else if B completes first, I need to execute function 2. HOw do I know which of the two threads has completed execution first?

推荐答案

import java.util.concurrent.Semaphore;

public class ThreadTest {
    private Semaphore semaphore = new Semaphore(0);
    private String winner;

    private synchronized void finished(String threadName) {
        if (winner == null) {
            winner = threadName;
        }
        semaphore.release();
    }

    public void run() {
        Runnable r1 = new Runnable() {
            public void run() {
                try {
                    Thread.sleep((long) (5000 * Math.random()));
                }
                catch (InterruptedException e) {
                    // ignore
                }
                finally {
                    finished("thread 1");
                }
            }
        };

        Runnable r2 = new Runnable() {
            public void run() {
                try {
                    Thread.sleep((long) (5000 * Math.random()));
                }
                catch (InterruptedException e) {
                    // ignore
                }
                finally {
                    finished("thread 2");
                }
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
        try {
            semaphore.acquire();
            System.out.println("The winner is " + winner);
        }
        catch (InterruptedException e) {
            System.out.println("No winner");
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        new ThreadTest().run();
    }
}

此解决方案的优势在于尽快获胜当第一个线程结束时,而不是必须等到所有线程都完成。

This solution has the advantage of having a winner as soon as the first thread finishes, instead of having to wait until all the threads are done.

编辑:

Aa, CountDownLatch 是这个问题的更好的抽象。因此可以写出相同的算法:

Aa indicated by jtahlborn, CountDownLatch is a better abstraction for this problem. The same algorithm can thus be written as this :

import java.util.concurrent.CountDownLatch;

public class ThreadTest {
    private CountDownLatch latch = new CountDownLatch(1);
    private String winner;

    private synchronized void finished(String threadName) {
        if (winner == null) {
            winner = threadName;
        }
        latch.countDown();
    }

    public void run() {
        Runnable r1 = new Runnable() {
            public void run() {
                try {
                    Thread.sleep((long) (5000 * Math.random()));
                }
                catch (InterruptedException e) {
                    // ignore
                }
                finally {
                    finished("thread 1");
                }
            }
        };

        Runnable r2 = new Runnable() {
            public void run() {
                try {
                    Thread.sleep((long) (5000 * Math.random()));
                }
                catch (InterruptedException e) {
                    // ignore
                }
                finally {
                    finished("thread 2");
                }
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
        try {
            latch.await();
            System.out.println("The winner is " + winner);
        }
        catch (InterruptedException e) {
            System.out.println("No winner");
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        new ThreadTest().run();
    }
}

如果你想等待两个线程完成在显示获胜者之前,您只需将锁存器初始化为2而不是1。

If you want to wait for the two threads to finish before displaying the winner, you just have to initialize the latch to 2 instead of 1.

这篇关于如何知道哪个线程首先从两个线程中完成执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆