How threads work in Java and how their working is different from basic code inside a method?

前端 未结 4 1403
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 10:11

Basically this code has two threads created in two classes, and they are called from the third class. Each thread has a loop, and it sleeps after each iteration.

(co

相关标签:
4条回答
  • 2020-12-10 10:47

    You can't predict in which order threads will be executed unless you control their execution (with mechanism like lock, mutex, semaphore and join).

    I think you need more knowledge about concurrency programming.

    Here some useful links:

    wikipedia's concurrency page

    oracle's tutorial (IMHO it's pretty good tutorial)

    0 讨论(0)
  • 2020-12-10 10:50

    Well, this is a common misconception, that java programs are single threaded by nature, because they are not. When you start a java program it's being executed inside a Java Virtual Machine, which starts several other threads to execute your code. Check this nice blog:

    http://blog.jamesdbloom.com/JVMInternals.html#jvm_system_threads

    In your case you most important is, that you start a main thread, which executes a main method. From there you start two separate threads Thread1 and Thread2, which are being scheduled to be executed, but you don't know when they will be picked up by the OS scheduler to be actually executed. It's not deterministic for many reasons:

    • you don't know what algorithm scheduler is using to pick up threads to be executed,
    • you don't know how many cores your processors have, your threads might run in parallel or serially
    • Just In Time compiler might rearrange and optimise your code,
    • CPU might rearrange reads and writes to IO to optimise the execution of your code,
    • you might have bugs in your code that lead to data races, race conditions, starvations etc.

    Java concurrency is a hard topic and the blog entry that I've sent you is a good place to start, go with it. For serious reading go here http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601.

    Good luck.

    0 讨论(0)
  • 2020-12-10 10:57

    I wouldn't really trust on whatever System.out.println() tells me, have you tried debugging and/or flushing the System.out stream after every println?

    There are a lot of factors that can affect the way threads are executed, for example, in this case what might be happening is that, by the time that Thread1 is created and run, the main Thread reaches "CHECK 1 CHECK" point, and this is why it's shown first.

    I'd recommend you to log the outputs and debug your code and see if the behavior is the same.

    Let us know what you discover so we can help you.

    Hope this helps (at least a bit) :)

    0 讨论(0)
  • 2020-12-10 11:01

    The execution of threads is quite Random. you can control the execution(by synchronization and all). Refer to docs.oracle for better understanding.

    0 讨论(0)
提交回复
热议问题