“Cannot reproduce” - is Java deterministic multithreading possible?

前端 未结 3 2022
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 03:45

Is this possible to run multithreaded Java application in a deterministic fashion? I mean to have always the same thread switching in two different runs of my application.

3条回答
  •  孤独总比滥情好
    2021-01-18 04:22

    As quoted by OldCurmudgeon, it's not possible with multi threading.

    If you decide to use single Thread, I prefer newSingleThreadExecutor to normal Thread due to flexibility and advantages of newSingleThreadExecutor

    Use

    newSingleThreadExecutor from Executors

    public static ExecutorService newSingleThreadExecutor()
    

    Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)

    Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

    Related SE questions:

    Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()

    ExecutorService vs Casual Thread Spawner

提交回复
热议问题