Day-10 Multithreading in Java

After a long time, I resumed my preparation for OCJP, I wasn’t able to study for last few days because my granddad died and my home is stormed with guests, i had to take my sister to Guntur(8 hrs from my place) for JEE Mains exam and to add I suffered a heat stroke, its been a hell, I tried to use flash cards as much as possible meanwhile to revise the topics I learned previously.

Today I learned about Threads in Java.

There are two ways  to define and start a thread in java

  1. By extending Thread class
  2. By implementing Runnable interface

Example program for defining a Thread by extending Thread class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MyThread extends Thread 
{
	public void run() //job of a thread
	{
		for (int i=0;i<10,i++ )
		{
			System.out.println("This is a new thread!");
		}
	}
}
class ThreadDemo
{
	public static void main(String[] args)
	{
		MyThread t = new MyThread(); //Instantiation of a Thread
		t.start();// starting a thread
		{
			System.out.println("This is from main!");
		}
	}
}

If multiple Threads are waiting for execution then the Thread which should be executed first is decided by ThreadScheduler.
Thread scheduler is a part of JVM so we cannot predict its behaviour.

Difference between function calls t.start() and t.run()

In case of t.start(), a new thread will be created which is responsible for execution of the run() method.

But, in case of t.run() method , no new thread will be created and run() will be executed like an ordinary method call. i.e., here entire output is produced by main() only.

Overloading of run()

Overloading of run() can be done but thread class start() always calls no arg run() only.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//overloading of run
class MyThread extends Thread 
{
	public void run()
	{
			System.out.println("This is from no arg run()");
	}
	public void run(int i)
	{
			System.out.println("This is from int arg run()");
	}
}
class ThreadDemo2
{
	public static void main(String[] args)
	{
		MyThread t = new MyThread();
		t.start();
		System.out.println("This is from main!");
	}
}
/* output 
This is from main!
This is from no arg run()
*/

What happens if we override start() ?

If we override start(), our start() will be executed like any ordinary method and no new Thread will be created.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//override start
class MyThread extends Thread 
{
	public void start()
	{
		System.out.println("Start Method");
	}
	public void run()
	{
			System.out.println("This is from run()");
	}	
}
class ThreadDemo4
{
	public static void main(String[] args)
	{
		MyThread t = new MyThread();
		t.start(); //this will be called like a normal method, here no thread is created
		System.out.println("This is from main!");
	}
}
/* output 
Start Method
This is from main!
*/
  • After starting of a thread, we should not should not try to restart it i.e. we should not call start() on a thread which is already started. If we do so we would get “IllegalThreadStateException”

Defining a Thread by implementing Runnable interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Creating a thread by implementing Runnable interface
class MyRunnable implements Runnable
{
	public void run()
	{
		System.out.println("Child Thread!");
	}
}
class ThreadDemo3
{
	public static void main(String[] args) 
	{
		MyRunnable r = new MyRunnable();
		Thread t = new Thread(r);
		t.start();
		System.out.println("Hello from main method!");
	}
}

Thread class constructors

  • Thread t = new Thread();
  • Thread t = new Thread(Runnable r);
  • Thread t = new Thread(String name);
  • Thread t = new Thread(Runnable r, String name);
  • Thread t = new Thread(ThreadGroup g, String name);
  • Thread t = new Thread(ThreadGroup g, Runnable r);
  • Thread t = new Thread(ThreadGroup g, Runnable r, String name);

To set and get name of the Thread

Every name in java has some name, it may be default name generated by JVM or it may be a name explicitly provided by programmer.

Thread class defines following methods to get and set names of Thread.

  1. public final static getName();
  2. public final void setName(String name);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//to get and set names of a thread
class MyThread extends Thread 
{
	public void run()
	{
			System.out.println("This is a new thread!");
	}
}
class ThreadDemo5
{
	public static void main(String[] args)
	{
		System.out.println(Thread.currentThread().getName()); //Main
		MyThread t = new MyThread();		
		System.out.println(t.getName()); //Thread-0
		//Now lets change the name of main
		Thread.currentThread().setName("Harsha");
		System.out.println(Thread.currentThread().getName());
		//System.out.println(10/0);
	}
}
/* If you remove comment in line 19, you can observe error like
Exception in thread "Harsha" java.lang.ArithmeticException: / by zero
        at ThreadDemo5.main(ThreadDemo5.java:19)
 
Observe it says harsha not main, hence we successfully changed the name of the thread
  • To get reference of current executing Thread reference we can use Thread.currentThread()

 Thread Priority

Every Thread in Java has some priority. Valid range of priorities is from 1 to 10 where 1 is least and 10 is the highest priority.

Thread class defines the three constants to represents standard priorities.

  1.  Thread.MIN_PRIORITY (value 1)
  2. Thread.MAX_PRIORITY (value 10)
  3. Thread.NORM_PRIORITY (value 5)

Thread scheduler uses Thread Priorities while allocating processor and obviously the Thread which has high priority will get more chance to execute.

The default priority of main thread in java is 5 and for remaining threads the default priority will be inherited from parent to child. We can change the priority of Threads by using following methods

  1. public final int getPriority()
  2. public final int setPriority()

Example program to set and get priorities of a Thread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyThread extends Thread 
{
	public void run()
	{
			System.out.println("This is a new thread!");
	}
}
class ThreadDemo6
{
	public static void main(String[] args)
	{
		System.out.println(Thread.currentThread().getPriority());
		MyThread t = new MyThread();
		System.out.println(t.getPriority());
		t.setPriority(Thread.MAX_PRIORITY);
	    System.out.println(t.getPriority());
		t.start();
		System.out.println("This is from main");
	}
}

Leave a Reply