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

前端 未结 4 1413
被撕碎了的回忆
被撕碎了的回忆 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: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.

提交回复
热议问题