小编Wil*_*ers的帖子

“java.lang.IllegalStateException:任务只能从 FX 应用程序线程使用”,尽管任务是从 FX 应用程序线程创建和运行的

我有一个单一场景的JavaFX应用程序,它运行一个动画,动画需要在两种状态之间来回切换。
基于“Java 如何编程,11/e,早期对象”中的示例 ,我编写了一个控制器,该控制器在初始化方法中创建类似的设置,
以及一个具有布尔值的任务,该任务用布尔值向动画计时器发出何时通过翻转切换状态的信号其值然后睡眠。无论
我做什么,我都会不断收到从该方法抛出的“java.lang.IllegalStateException:任务只能从 FX 应用程序线程使用” 。call()

这是控制器的简化版本:

public class AnimationController {
    @FXML public AnimationTimer myAnimationTimerExtention;
    private ExecutorService executorService;

   public void initialize() {
        myAnimationTimerExtention.setState(false);
        TimeingTask task = new TimeingTask (Duration.ofSeconds(5));

        task .valueProperty().addListener((observableValue, oldValue, newValue) -> {
            myAnimationTimerExtention.setState(false);
        });

        executorService = Executors.newFixedThreadPool(1);
        executorService.execute(timeTrafficLightTask);
        executorService.shutdown();
    }
Run Code Online (Sandbox Code Playgroud)

这是我的任务:

public class TimeingTask  extends Task<Boolean> {
    private final Duration duration;

    public TimeingTask(Duration duration) {
        this.duration = duration;
        updateValue(true);
    }

    @Override
    protected Boolean call() throws Exception {
        while (!isCancelled()) {
            updateValue(!getValue()); …
Run Code Online (Sandbox Code Playgroud)

java concurrency user-interface animation javafx

-2
推荐指数
1
解决办法
202
查看次数

等待互斥锁而不获取它

我一直在编写一个小型微服务,因此熟悉 Go 及其并发机制。

在我的程序中,我有一个具有状态的结构,我想同步该状态,以便多个 goroutine 能够读取它,但不能在另一个 goroutine 更新该状态时进行。

最初我认为 RWMutax 是我需要的,但是根据文档,只有一个 goroutine 可以在任何给定的时刻获得读锁。我要走这条线:

“如果一个 goroutine 持有一个用于读取的 RWMutex,而另一个 goroutine 可能会调用 Lock,那么在初始读锁被释放之前,任何 goroutine 都不应该期望能够获得一个读锁。”

有没有办法在不获取锁的情况下等待互斥锁?

类似的东西:

type stateful struct {
    state        int
    stateMutex   sync.Mutex
    beingUpdated bool
}

type Stateful interface {
    GetState() int
    SetState(st int)
}

func createStateful (sa string) stateful {
    return server{state: 0, stateMutex: sync.Mutex{}, beingUpdated: false}
}

func (s *stateful) SetState(st int) {
    s.stateMutex.Lock()
    s.beingUpdated = true
    s.state = st
    s.beingUpdated = false
    s.stateMutex.Unlock()
}

func (s *stateful) GetState() …
Run Code Online (Sandbox Code Playgroud)

concurrency mutex go

-5
推荐指数
1
解决办法
98
查看次数

标签 统计

concurrency ×2

animation ×1

go ×1

java ×1

javafx ×1

mutex ×1

user-interface ×1