侦听器和线程

时间:2018-12-20 18:59:24

标签: java multithreading listener

我觉得这可能是一个愚蠢的问题,但是我对听众的经验并不丰富……无论如何,我对线程和听众都有疑问;考虑下面的代码(语法上可能不正确,这是我的首要任务):

public class Stuff {
    private SimpleLongProperty time = new LongProperty(this, "time");
    private Executor execute;

    public Stuff(Clock clock) {
        time.bind(clock.getValue);
        execute = Executors.newFixedThreadPool(5);
    }

    public void someAction() {
        for(int i = 0; i < 5; i++) {
            execute.execute(scheduleTask());
        }
    }

    public Runnable scheduleTask() {
        time.addListener((obs, oldV, newV) -> {
            //Code here
        });
    }
}

当调用someAction()并调用scheduleTask()5次以添加5个侦听器时,每个侦听器都将在更新时间时在自己的线程内执行代码吗?还是会因为时间而在主线程中执行代码?

1 个答案:

答案 0 :(得分:0)

能够上工作站编写代码并对其进行测试,找到了我的答案。

public class Stuff {
    private LongProperty time = new SimpleLongProperty(this, "time");
    private Executor execute;

    public Stuff(Clock clock) {
        time.bind(clock.getValue);
        execute = Executors.newCachedThreadPool(runnable -> {
            Thread t = new Thread(runnable);
            t.setDaemon(true);
            return t;
        });
    }

    public void someAction() {
        for(int i = 0; i < 5; i++) {
            execute.execute(scheduleTask(i));
        }
    }

    public Runnable scheduleTask(int i) {
        time.addListener((obs, oldV, newV) -> {
            System.out.println("Task " + i + ": " + Thread.currentThread());
        });
    }
}

上面的代码将显示:

Task 0: Thread[JavaFX Application Thread, 5, main]
Task 1: Thread[JavaFX Application Thread, 5, main]
Task 2: Thread[JavaFX Application Thread, 5, main]
Task 3: Thread[JavaFX Application Thread, 5, main]
Task 4: Thread[JavaFX Application Thread, 5, main]

将someAction()和scheduleTask()函数更改为如下所示:

public void someAction() {
    for(int i = 0; i < 5; i++) {
        scheduleTask(i);
    }
}

public void scheduleTask(int i) {
    Runnable test = () -> {
        System.out.println("Task " + i + ": " + Thread.currentThread());
    };
    time.addListener((obs, oldV, newV) -> {
        execute.execute(test);
    });
}

将产生以下内容:

Task 0: Thread[Thread-16, 5, main]
Task 1: Thread[Thread-17, 5, main]
Task 2: Thread[Thread-20, 5, main]
Task 3: Thread[Thread-19, 5, main]
Task 4: Thread[Thread-18, 5, main]