TIL: Java Multithreading Intro
I went ahead and started to look into multithreading in java tonight, because I know it’s going to be something I’ll need to understand fairly soon. I’m not sure if different libraries implement it without any real work on the users part, but I figured it would be good to start with the basics.
Everything here comes from a tutorial I found earlier on youtube. I’m not sure how great of a source this really is, but I liked that the example showed what all is required to get threading working in a super basic example.
So by default, java applications will run completely single threaded. Everything runs in the single
main thread. When you’ve got failures within your program, you’ll notice that the failures are occuring within that
In order to make use of multi threading, classes have to be created extending threads. This will allow the method to be executed in its own thread, rather than being executed by main. In order for the threads to start, main will need to initially kick them off.
In addition to extending
Thread, the class must also implement a
run() method with what will be executed when the thread starts.
Finally, that thread will get started by main with a call to the
Here’s the simple program that shows how this all fits together: