Java threads

Before defining a thread, it is important to understand the following terms.

Multitasking is the ability to perform several tasks simultanously and it divided into process based and thread based.

1- Multiprocessing is the abililty to run more than one process (application) at the same time. An example is running Excel and Photoshop at the same time.

2- Multithreading is the ability to perform more than one activity within the same process. An example is using your web browser (a process) to read info on internet, send an email and download a file. Those are three threads within one process(application).

thread_states_life_cycle

What is a thread in Java?

A Thread is a Java class implements the Runnable interface. Every application (process) has one or more threads. Threads share process’s resources, including memory and open files. There are two types of threads in Java namely: daemon threads and user threads. 

Most daemon threads are created by JVM as the garbage collection, while user threads are mostly created by programmers. Daemon threads are usually designed to run in the background. One of the common threads that every programmer works with is the main thread

How to create threads?

You can create threads in two different ways:

  1. Extending the class Thread to inherit all its functionalities.
  2. Implementing the Runnable interface, which contains only a run method. Programmers need to override the run method.

To start your thread you need to call the start() method, which calls the run() method.

 

Example 1: How to print the name of the main thread to the standard output?

In this easy example, we print the name of the currently running thread to the standard output using the getName() method and the currentThread() method.

public class MainThreadName{

	public static void main(String[] args){
		// currentThread() returns a reference to the currently running thread.
		Thread runningThread = Thread.currentThread();
		// getName() returns the thread's name
		System.out.println("The thread name is: " + runningThread.getName());
	}
}

Answer example 1:

This code writes: “The thread name is: main” to the standard output.

 

The two methods by creating threads have advantages and disadvantages:

By extending the Thread class you inherit all the functionalities of the class and that makes it easier for programmers. However, Java does not support multiple inheritance and that prevent programmers to inherit from another class.

In term of design, the Thread class may not be the right super class for your class.
By implementing the Runnable interface, your class can inherit from another appropriate superclass. Which is why making the decision of which method the programmers choose is important.

The following two examples shows how to create threads by extending the Thread class as well as implementing the interface Runnable.

 

Example 2: How to create a thread by subclassing the Thread class?

The following simple example is creating a thread by extending a Thread class.

public class MyThread extends Thread{

	public void run(){
		while(true){
			System.out.println("MyThread......." + getName());
		}
	}
	public static void main(String[] args){

		MyThread myThread = new MyThread();
		//myThread.setName("myThread");
		myThread.start();
		Thread thisThread = Thread.currentThread();

		while(true){
			System.out.println("Main thread....." + thisThread.getName());
		}
	}
}

This code writes a combination of Main and myRunnable to the standard output as shown below!

Main thread…..main
Main thread…..main
MyThread…….Thread-0
MyThread…….Thread-0
MyThread…….Thread-0
Main thread…..main
Main thread…..main
MyThread…….Thread-0

The name Thread-0 is a standard name of the thread. You can change the name by using the setName method. By uuncommenting line 11 the thread name will change from Thread-0 to myThread as shown below.

MyThread…….myThread
MyThread…….myThread
Main thread…..main
Main thread…..main
MyThread…….myThread
Main thread…..main
Main thread…..main

Example 2: How to create a thread by implementing the Runnable interface?

The following simple example is creating a thread by implementing the Runnable interface.

public class MyRunnable implements Runnable{

	public void run(){
		while(true){
			System.out.println("MyRunnable..........");
		}
	}
	public static void main(String[] args){

		Thread myRunnable = new Thread(new MyRunnable());
		myRunnable.start();

		while(true){
			System.out.println("Main thread...............");
		}
	}
}

This code writes a combination of Main and myRunnable to the standard output as shown below!

MyRunnable……….
Main thread……………
Main thread……………
Main thread……………

MyRunnable……….
MyRunnable……….

Thread States

See the above illustration of the thread life cycle and states.

1- New Thread

By instantiating a Thread, it is in a new state before it is started.

MyThread myThread = new MyThread();

2- Runnable

A thread is runnable after calling its start() method.

myThread.start();

3- Not Runnable

A thread is not runnable after calling the method suspend().

MyThread.suspend();

4- Dead

A thread is dead once it has been explicitly stopped.

 

Some useful constructors and methods of the class Thread.

Constructors

Thread():  Assigns a new Thread object.

Thread(String name): Assigns a new Thread object.

Thread(Runnable runnable): Assigns a new Thread object by passing a Runnable object.

Methods

Return types and description

currentThread() static Thread

Returns a reference to the current thread.

getId() long

Returns the id of a thread.

getName() String

Returns the name of a thread

getPriority() int
Returns an int represents the thread’s priority.
 

getState()

Thread.State
Returns the state of the thread.
isDaemon() boolean
checks whether a thread is a daemon thread.
isInterrupted() boolean
checks whether this thread has been interrupted.
join() void

Waits for the death of the thread.

run()

 

void
If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.
setName(String name) void

By passing a string parameter to this method, you can change the name of the thread.

setPriority(int newPriority) void
By passing an int parameter, you can change the priority of a thread.You can assign a priority from (1 to 10) to any Java thread. Usually, it is not necessary to assign the priority of threads, because threads receive automatically a priority of 5.
sleep(long millis) static void
This method allows the thread to sleep for a specific time of milliseconds.
start() void
By invoking the start method the Java Virtual Machine calls the run method of this thread.
yield() static void

A hint to the scheduler that the current thread is willing to yield its current use of a processor.

 stop() void
Deprecated.
 suspend() void
Deprecated.
 resume() void

Deprecated.

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

 


Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

2 Comments

Add a Comment
  1. Learning Java from quizzes is a great method!

  2. At last! Someone who undtdseanrs! Thanks for posting!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017