Keywords: Concurrency, Java Multithreading, Threads
Multithreading is an essential feature of Java. In this tutorial I will focus on explaining the basics of Java Threads, how to use them and how to feel comfortable with them. You will find lots of examples focused on single feature or method. Learning through examples is usually the best way to understand programming languages. For running these examples you can use an IDE like Eclispe or Netbeans, and if you don’t like to install them you can search for an online Java IDE.
What is Java thread?
Threads are lightweight processes used by Java to support concurrency. All Java programs has at least one thread – the main thread, created by the JVM at the start of the program and executing the content of the main method. Every Java thread is created and managed by Thread class.
How to create threads in Java?
Each thread is associated with an instance of Thread. You can create threads in two different ways
- With Thread instance
- Separating the thread logic from its management
Here are two very basic examples of the two different approaches – create another thread:
First I will subclass Thread
And the next one will implements Runnable. At the end you again need to create a thread instance and pass the Runnable object to it.
How to manage a thread
Sleep – its time to sleep
The sleep method is used to suspend the current thread execution for a fixed amount of time and its used to make execution time available for other threads. Keep in mind that sleep time is not precise because it relies on the OS running on this device. So you can’t be sure if the thread will sleep the given time period precisely – and this question is often used in Java tests, especially job tests.
Also keep in mind that the method sleep throws InterruptedException and you must state that your method throws it or you need to add a try-catch block.
Example of using Thread.sleep:
And the result of the code above:
We have another thread!
Buy from main thread
I like to sleep
Join (join the dark side) or at least Thread.join
This method allows one thread to wait for the completion of another. The current thread pauses and the thread which join method is called takes over. You can specify a time period but again like sleep the time period is not precise and depends on the OS.
Here is the same example with join:
This will be the end of part one. Part two will look at synchronization and a bit of more complex topics about Java Threads.