Multithreading in java
Multithreading:
A thread is the flow of execution of a single set of program statements. Multithreading consists of multiple sets of statements which can be run in parallel. With a single processor only one thread can run at a time but strategies are used to make it appear as if the threads are running simultaneously. Depending on the operating system, either time slicing or interrupt methods will move the processing from one thread to the next.
Threads exist in several states
– Running
– Ready (to run)
– Suspended
– Resumed
– Blocked
– Terminated (can not be resumed)
There are two ways to implements threads in java
The Thread Class allows multitasking (i.e. running several tasks at the same time) by instantiating (i.e. creating) many threaded objects, each with their own run time characteristics. One way is to extend the Thread class and override the run() method such as:
A thread is the flow of execution of a single set of program statements. Multithreading consists of multiple sets of statements which can be run in parallel. With a single processor only one thread can run at a time but strategies are used to make it appear as if the threads are running simultaneously. Depending on the operating system, either time slicing or interrupt methods will move the processing from one thread to the next.
Threads exist in several states
– Running
– Ready (to run)
– Suspended
– Resumed
– Blocked
– Terminated (can not be resumed)
There are two ways to implements threads in java
- using thread class
- using runnable interface
The Thread Class allows multitasking (i.e. running several tasks at the same time) by instantiating (i.e. creating) many threaded objects, each with their own run time characteristics. One way is to extend the Thread class and override the run() method such as:
package
aurangzeb.utk.com;
public class HelloThread extends Thread {
public void run()
{
for (int x = 0; x <
100; ++x)
System.out.print(" Hello
");
}
}
Using runnable interface:
However if you need to inherit from another class as well, you can implement a Runnable interface instead.
package
aurangzeb.utk.com;
public class HelloThread implements Runnable {
Thread
t = new Thread(this);
t.start();
public void run() {
for (int x = 0; x <
100; ++x) {
System.out.print(" Hello
");
}
}
}
Thread object methods are used on instantiated thread objects to control the thread appropriately. These methods include run(), start(), sleep(longInt), join(), isAlive(), currentThread(), getName(), setName(string), getPriority() and setPriority(int).
Some older methods such as stop(), suspend() and resume() have been deprecated as they sometimes caused system instability or hangup! A better way of stopping a thread is making the run method into a while loop based on a logical that can be set to false as in:
public void run() {
while (okToRun==true)
{ // do the run time stuff here
}
}
Assigning Priority:
Priority is ranking. Some threads can either run for a longer timeslice or run more often (depending on the operating system). Peers (or equals) get the same time/number of runs. Priority is set from MIN_PRIORITY (currently 1) to MAX_PRIORITY (currently 10) using the setPriority(int) method. NORM_PRIORITY is the midrange value (currently 5). These constants are defined in the Thread class.
In order to start a thread
– Call the thread’s start() method
– It causes the thread’s run() method to be called in that separately executing thread
– Call the thread’s start() method
– It causes the thread’s run() method to be called in that separately executing thread
- An instance of class Thread can be created by calling any of the overloaded constructors of the class
- Thread t = new Thread();
- t.start();
- When ‘start()’ is called on an object of Thread
If object was constructed using a separate Runnable object, then that Runnable object's run() method is called Otherwise, the run() method in Thread class is called
- This method does nothing by default and simply returns
- Should be overridden by subclasses!
- When Java program starts, one thread begins running immediately main thread
Called automatically when program starts
- It is the thread from which other ‘child’ threads can be spawned
- Often, it must be the last thread to finish execution because it performs various shutdown actions
- We can get a reference of it by calling a method in the Thread class
public static Thread currentThread ()
- Returns a reference to the thread in which it is called
Code Examples:
package
aurangzeb.utk.com;
import java.io.*;
public class Mythread extends Thread {
public static void main(String[]
args) {
Thread
t = Thread.currentThread();
System.out.println("The
current thread is: " + t);
t.setName("MyJavaThread");
System.out.println("new name
of thread is: " + t);
try {
for (int i = 0; i <
3; i++) {
System.out.println(i);
Thread.sleep(1500);
}
}
catch
(InterruptedException e) {
System.out.println("Main
Thread interrupted");
}
}
}
Code output:
The current thread is: Thread[main,5,main]
new name of thread is: Thread[MyJavaThread,5,main]
0
1
2
new name of thread is: Thread[MyJavaThread,5,main]
0
1
2
Code Example:
package
aurangzeb.utk.com;
import java.io.*;
public class ThreadTester {
public static void main(String[]
args) {
PrintThread
thread1, thread2, thread3, thread4;
thread1
= new PrintThread("thread1", 1000);
thread2
= new PrintThread("thread2", 1500);
thread3
= new PrintThread("thread3", 2000);
thread4
= new PrintThread("thread4", 2500);
System.out.println("Starting
Threads");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
System.out.println("Threads
started");
}
}
class PrintThread extends Thread {
private int sleepTime;
public
PrintThread(String name, int st) {
/* sleep
between 0 and 5 */
sleepTime = (int) (Math.random()
* 5000);
// sleepTime =
st;
System.out.println("Name is:
" + getName() + "; Sleep: " + sleepTime);
}
public void run() {
try {
System.out.println(getName()
+ "
going to sleep");
Thread.sleep(sleepTime);
}
catch
(InterruptedException e) {
System.out.println("Thread
interrupted");
}
System.out.println(getName()
+ "
End of sleeping");
}
}
output:
Name is: Thread-0; Sleep: 4702
Name is: Thread-1; Sleep: 2046
Name is: Thread-2; Sleep: 3395
Name is: Thread-3; Sleep: 4736
Starting Threads
Thread-0 going to sleep
Threads started
Thread-2 going to sleep
Thread-1 going to sleep
Thread-3 going to sleep
Thread-1 End of sleeping
Thread-2 End of sleeping
Thread-0 End of sleeping
Thread-3 End of sleeping
Code Example
Name is: Thread-1; Sleep: 2046
Name is: Thread-2; Sleep: 3395
Name is: Thread-3; Sleep: 4736
Starting Threads
Thread-0 going to sleep
Threads started
Thread-2 going to sleep
Thread-1 going to sleep
Thread-3 going to sleep
Thread-1 End of sleeping
Thread-2 End of sleeping
Thread-0 End of sleeping
Thread-3 End of sleeping
Code Example
