java - 跟踪执行线程

标签 java multithreading concurrency

我想弄清楚如何跟踪我的应用程序生成的所有线程。最初,我以为我已经使用 CyclicBarrier 解决了这个问题,但是我看到线程在我的 await 调用之后执行。

下面是工作伪代码:

public class ThreadTesterRunner {

    public static void main(String[] args) throws InterruptedException {

        final CyclicBarrier cb = new CyclicBarrier(1);
        ThreadRunner tr = new ThreadRunner(cb);
        Thread t = new Thread(tr, "Thread Runner");
        t.start();

        boolean process = true;
        // wait until all threads process, then print reports
        while (process){
            if(tr.getIsFinished()){
                System.out.println("Print metrics");
                process = false;
            }
            Thread.sleep(1000);
        }
    }
}


class ThreadRunner implements Runnable {
    static int timeOutTime = 2;
    private ExecutorService executorService = Executors.newFixedThreadPool(10);
    private final CyclicBarrier barrier;
    private boolean isFinished=false;

    public ThreadRunner(CyclicBarrier cb) {
        this.barrier = cb;
    }

    public void run(){
        try {
            boolean stillLoop = true; int i = 0;
            while (stillLoop){
                int size;
                Future<Integer> future = null;
                try {
                    future = executorService.submit(new Reader()); // sleeps
                    size = future.get();
                } catch (InterruptedException | ExecutionException ex) {
                    // handle Errs
                }

                if(i == 3){
                    stillLoop = false;
                    this.barrier.await();
                    this.isFinished=true;
                }
                //System.out.println("i = "+i+"  Size is: "+size+"\r");
                i++;
            }
        } catch (InterruptedException | BrokenBarrierException e1) {
            e1.printStackTrace();
        }
    }

    public boolean getIsFinished(){
        return this.isFinished;
    }
}

class Reader implements Callable {
    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    @Override
    public Object call() throws Exception {
        System.out.println("Reading...");
        Thread.sleep(2000);
        executorService.submit(new Writer());
        return 1000;
    }
}

class Writer implements Callable {
    @Override
    public Void call() throws Exception {
        Thread.sleep(4000);
        System.out.println("Wrote");    
        return null;
    }
}

谁能建议一种在所有线程运行后只打印“打印指标”的方法?

最佳答案

您似乎没有做任何事情来协调您的 ReaderWriter 线程,而这正是您要等待的线程。如果您将同步屏障传递给这些线程,以便它们可以在完成时注册并发出信号,那么它就可以正常工作。

这是为此重写的版本,使用 Phaser 而不是 CyclicBarrier。请注意,每个 ReaderWriter 在构造时注册自己,并在执行完成时通知同步屏障:

public class ThreadTesterRunner {
    public static void main(String[] args) throws InterruptedException {
        final Phaser cb = new Phaser();
        ThreadRunner tr = new ThreadRunner(cb);
        Thread t = new Thread(tr, "Thread Runner");
        t.start();

        boolean process = true;
        // wait until all threads process, then print reports
        while (process){
            if(tr.getIsFinished()){
                System.out.println("Print metrics");
                process = false;
            }
            //else {
            //  System.out.println("Waiting:  registered=" + cb.getRegisteredParties() + ", arrived=" + cb.getArrivedParties() + ", unarrived=" + cb.getUnarrivedParties());
            //}
            Thread.sleep(1000);
        }
    }
}


class ThreadRunner implements Runnable {
    static int timeOutTime = 2;
    private ExecutorService executorService = Executors.newFixedThreadPool(10);
    private final Phaser barrier;
    private boolean isFinished=false;

    public ThreadRunner(Phaser phaser) {
        this.barrier = phaser;
    }

    public void run(){
        try {
            boolean stillLoop = true; int i = 0;
            while (stillLoop){
                int size;
                Future<Integer> future = null;
                try {
                    future = executorService.submit(new Reader(this.barrier)); // sleeps
                    size = future.get();
                } catch (InterruptedException | ExecutionException ex) {
                    // handle Errs
                }

                if(i == 3){
                    stillLoop = false;
                    this.barrier.awaitAdvance(0);
                    this.isFinished=true;
                }
                //System.out.println("i = "+i+"  Size is: "+size+"\r");
                i++;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public boolean getIsFinished(){
        return this.isFinished;
    }
}

class Reader implements Callable {
    private Phaser barrier;
    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public Reader(Phaser phase) {
        phase.register();
        this.barrier = phase;
    }

    @Override
    public Object call() throws Exception {
        System.out.println("Reading...");
        Thread.sleep(2000);
        executorService.submit(new Writer(this.barrier));
        this.barrier.arrive();
        return 1000;
    }
}

class Writer implements Callable {
    private Phaser barrier;

    public Writer(Phaser phase) {
        phase.register();
        this.barrier = phase;
    }

    @Override
    public Void call() throws Exception {
        Thread.sleep(4000);
        System.out.println("Wrote");
        this.barrier.arrive();
        return null;
    }
}

关于java - 跟踪执行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165042/

相关文章:

java - 消除方形边缘按钮java

java - 线程安全和线程兼容有什么区别?

java - 根据不断变化的 map 对数组进行排序

java - 使用正则表达式替换链接标签

java - Spring 组件在未 Autowiring /注入(inject)时是否会实例化?

java - Libgdx:骨架存储动画和移动网格部件

python - 将带有 **kwargs 错误的值线程化并传递给 TypeError

c# - 多线程与顺序处理的效果如何?

java - 我如何为 Java 队列/列表自动执行 "enqueue if free space OR dequeue then enqueue"?

mongodb - 具有基于行/文档的写锁的数据库