Unit1
Unit1
Contents
•Lightweight process.
Thread Class
A Thread class has several methods and constructors which allow us to
perform various operations on a thread. The Thread class extends
the Object class. The Object class implements the Runnable interface. The
thread class has the following constructors that are used to perform various
operations.
•Thread()
•Thread(String name)
•Thread(Runnable r)
•Thread(Runnable r,String name)
Commonly used methods of Thread class:
Starting a thread:
Output:thread is running...
Extending the thread class :
Output:thread is running...
Example program:
class x implements Runnable
{ //1 STEP
public void run()
{ //2 STEP
for(int i=0;i<=5;i++)
System.out.println("The Thread x is:"+i);
System.out.println("End of the Thread x");
}
}
class RunnableTest
{
public static void main(String args[])
{
x r=new x();
Thread threadx=new Thread(r);
threadx.start();
System.out.println("The end of the main thread");
}
}
Runnable interface is having following steps:
It is often very important to know which thread is ended. This helps to prevent
the main from terminating before the child Thread is terminating. To address
this problem "Thread" class provides two methods: 1) Thread.isAlive() 2)
Thread.join().
The general form of the "isAlive()" method is as follows:
final boolean isAlive();
This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread
is alive, returns "FALSE" otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly
use to wait for a thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates
Priority of a Thread (Thread Priority):
5
100
10
200
15
300
20
400
25
500
In the above output, it can be observed
that both the threads are simultaneously
accessing the Table object to print the
table. Thread1 prints one line and goes to
sleep, 400 milliseconds, and Thread1
prints its task.
Using the Java synchronized method
If you declare any method as synchronized, it is known as
synchronized method. Synchronized method is used to lock an
object for any shared resource. When a thread invokes a
synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}
where synchronized is the keyword, method contains the type,
and method_name represents the name of the method, and
para_list indicate the list of the parameters.
class Table {
// Synchronized method to print the table
synchronized void printTable(int n) {
for(int i = 1; i <= 5; i++) {
// Print the multiplication result
System.out.println(n * i);
try {
// Pause execution for 400
milliseconds
Thread.sleep(400);
} catch(Exception e) {
// Handle any exceptions
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 5
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread2(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 100
t.printTable(100);
}
}
public class TestSynchronization2 {
public static void main(String args[]) {
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2 objects with the
same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
In the above output it can be observed that when Thread1 is
accessing the Table object, Thread2 is not allowed to access
it. Thread1 preempts the Thread2 from accessing the
printTable() method.
Note:
1. This way of communications between the threads
competing for same resource is called implicit
communication.
2. This has one disadvantage due to polling. The polling
wastes the CPU time. To save the CPU time, it is preferred to
go to the inter-thread communication.
Inter-Thread Communication
• If two or more Threads are communicating with each
other, it is called "inter thread" communication.
Blocking Thread
A thread can be temporarily suspended or blocked from
entering into the runnable and running state by using the
following methods:
}
public class MovieBook
{
public static void main(String[] args) throws InterruptedException
{
TotalEarnings te=new TotalEarnings();
te.start();
synchronized(te)
{
te.wait();
System.out.println("total earnings :"+te.total);
}
}
}
// Two threads performing two tasks at a time.
public class MyThreadd extends Thread
{
// Declare a String variable to represent task.
String task;
MyThreadd(String task)
{
this.task = task;
}
public void run()
{
for(int i = 1; i <= 5; i++)
{
System.out.println(task+ " : " +i);
try {
Thread.sleep(1000); // Pause the thread execution for
1000 milliseconds.
} catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
} // end of for loop.
} // end of run() method.
public static void main(String[] args)
{
// Create two thread objects to represent two tasks.
// Passing task as an argument to its constructor.
MyThreadd th1 = new MyThreadd("Cut the ticket");
MyThreadd th2 = new MyThreadd("Show your seat number");