Oops - Unit Iv Notes
Oops - Unit Iv Notes
4.1.1 Multithreading
A multithreaded program runs two or more programs run
concurrently. Each part of such a program is called a thread, and
each thread defines a separate path of execution.
4.1.2 Multitasking
Multitasking is the process of running two or more programs
concurrently. There are two types
1. Process based multitasking-A process is nothing but a
program that is executing. It is the feature that runs two or
more programs concurrently.
1
4. Blocked State
5. Dead State
A thread can move from one state to another state. It is always
in one of these five states.
1.Newborn State
When we create a thread object, the thread is born and is said to
be newborn -state. In this state, we can do the following tasks
Schedule a thread for running using start() method
Kill a thread using stop() method
2
2. Runnable State
The runnable state means that the thread is ready for execution
and is waiting for the availability of the processor.The thread is
waiting in the queue for its execution.If all threads have equal
priority,then they are given time slots for execution in round-
robin fashion,that means first-come,first-serve manner.This
process of assigning time to threads is known as time-slicing.
If we want a thread to relinquish control to another thread to
equal priority before it turns comes, we can do the same by using
yield() method.
3. Running State
Running means that the thread is allotted with the processor for
its execution.The thread runs until higher priority thread comes.A
running thread may relinquish its control in one of the following
situations
a)suspend() method:
We can suspend the running thread for some time by using
suspend() method. A suspended thread may resume by using
resume() method.
3
period.The thread re-enters into runnable state as soon as this
time period is elapsed.
4. Blocked State
A thread is said to be blocked when it is prevented from entering
into the runnable state and subsequently the running state. This
happens when the thread is suspended, sleeping, or waiting in
order to satisfy certain requirements. A blocked thread is
considered “not runnable” but not dead and fully qualified to run
again.
5. Dead State
Every thread has a life cycle. A running thread ends its life when
it has completed executing its run() method. It is a natural death.
We can kill it by sending the stop message to it at any state.
4
Syntax:
public void run()
{
...........
...........
........... //Statements for implementing thread
}
5
• Often, it must be the last thread to finish execution
because it performs various
shutdown actions.
Output:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
6
5
4
3
2
1
Example Program:
class NewThread implements Runnable
{
Thread t;
NewThread()
{
7
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[ ] )
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
8
}
System.out.println("Main thread exiting.");
}
}
Output:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Example Program:
class NewThread extends Thread
{
NewThread()
{
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
9
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread(); // create a new thread
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
10
}
Output:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Example Program:
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
11
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
12
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
Syntax:
final boolean isAlive( )
join() method
The method that you will more commonly use to wait for a thread
to finish is called join( )
Syntax:
final void join( ) throws InterruptedException
13
This method waits until the thread on which it is called
terminates. join( ) allow you to specify a maximum amount of
time that you want to wait for the specified thread to terminate.
Example Program:
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin
{
public static void main(String args[])
{
14
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
15
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
Syntax:
ThreadName.setPriority(intNumber);
MIN_PRORITY = 1
NORM_PRORITY = 5
MAX_PRORITY = 10
16
Whenever multiple thread are ready for execution, the Java
system chooses the highest priority and executes it. If another
thread of a higher priority comes, the currently running thread is
preempted by the incoming thread. Now preempted thread
thread goes to runnable state.
Example Program:
class A extends Thread
{
public void run()
{
System.out.println("threadA started");
for(int i=1;i<=4;i++)
{
System.out.println("From Thread A:i="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("threadB started");
for(int j=1;j<=4;j++)
{
System.out.println("From Thread B: j="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
System.out.println("threadC started");
for(int k=1;k<=4;k++)
{
17
System.out.println("From Thread C: k="+k);
}
System.out.println("Exit from C");
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Start thread
A"); threadA.start();
System.out.println("Start thread
B"); threadB.start();
System.out.println("Start thread
C"); threadC.start();
Output:
Start thread A
Start thread B
Start thread C
threadB started
From Thread B : j=1
From Thread B : j=2
18
threadC started
From Thread C : k=1
From Thread C : k=2
From Thread C : k=3
From Thread C : k=4
Exit from C
End of main thread
From Thread B : j=3
From Thread B : j=4
Exit from B
threadA started
From Thread A : i=1
From Thread A : i=2
From Thread A : i=3
From Thread A : i=4
Exit from A
19
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
20
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
Output:
5
100
10
21
200
15
300
20
400
25
500
22
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
23
4.4.3.2 Synchronized Block
Synchronized block can be used to perform synchronization on
any specific resource of the method.Suppose you have 50 lines of
code in your method, but you want to synchronize only 5 lines,
you can use synchronized block.If you put all the codes of the
method in the synchronized block, it will work same as the
synchronized method.
Syntax:
synchronized (object reference expression)
{
//code block
}
Example program:
class Table
{
void printTable(int n)
{
synchronized(this)
{//synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
24
}
}//end of the method
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
25
Output:
5
10
15
20
25
100
200
300
400
500
Example Program:
class Table
{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){}
}
}
}
class MyThread1 extends Thread
{
public void run()
{
Table.printTable(1);
26
}
}
class MyThread2 extends Thread
{
public void run()
{
Table.printTable(10);
}
}
class MyThread3 extends Thread
{
public void run()
{
Table.printTable(100);
}
}
class MyThread4 extends Thread
{
public void run()
{
Table.printTable(1000);
}
}
public class TestSynchronization4
{
public static void main(String t[])
{
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
27
Output:
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
28
8000
9000
10000
Example Program:
class Q
29
{
int n;
synchronized int get()
{
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n)
{
this.n = n;
System.out.println("Put: " + n);
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
30
public void run()
{
while(true)
{
q.get();
}
}
}
class PC
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Output:
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
31
of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
There are many java daemon threads running automatically e.g.
gc, finalizer etc.
You can see all the detail by typing the jconsole in the command
prompt. The jconsole tool provides information about the loaded
classes, memory usage, running threads etc.
32
}
public static void main(String[] args)
{
TestDaemonThread1 t1=new TestDaemonThread1();//creating th
read
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work
user thread work
Constructors:
1. public ThreadGroup(String name): Constructs a new
thread group. The parent of this new group is the thread
group of the currently running thread.
2. public ThreadGroup(ThreadGroup parent, String
name): Creates a new thread group. The parent of this new
group is the specified thread group.
33
Methods:
1. int activeCount(): This method returns the number of threads
in the group plus any group for which this thread is parent.
Example Program:
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 1000; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
}
}
public class ThreadGroupDemo
{
public static void main(String arg[])
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("parent thread group");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting one");
NewThread t2 = new NewThread("two", gfg);
34
System.out.println("Starting two");
// checking the number of active thread
System.out.println("number of active thread: "+
gfg.activeCount());
}
}
Output:
Starting one
Starting two
number of active thread: 2
Example Program:
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 1000; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
35
System.out.println(Thread.currentThread().getName()+ "finished
executing");
}
}
public class ThreadGroupDemo1
{
public static void main(String arg[]) throws InterruptedException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("gfg");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting one");
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting two");
// checking the number of active thread
System.out.println("number of active thread group: "+
gfg.activeGroupCount());
}
}
Output:
Starting one
Starting two
number of active thread group: 2
one finished executing
two finished executing
Example Program:
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
36
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 1000; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
System.out.println(Thread.currentThread().getName() + "
finished executing");
}
}
public class ThreadGroupDemo2
{
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting one");
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting two");
gfg.checkAccess();
System.out.println(gfg.getName() + " has access");
gfg_child.checkAccess();
System.out.println(gfg_child.getName() + " has access");
}
}
37
Output:
Starting one
Starting two
Parent thread has access
child thread has access
one finished executing
two finished executing
Example Program:
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
}
}
public class ThreadGroupDemo3
{
38
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting one");
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting two");
// block until other thread is finished
t1.join();
t2.join();
// destroying child thread
gfg_child.destroy();
System.out.println(gfg_child.getName() + " destroyed");
// destroying parent thread
gfg.destroy();
System.out.println(gfg.getName() + " destroyed");
}
}
Output:
Starting one
Starting two
child thread destroyed
Parent thread destroyed
Example Program:
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
39
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
System.out.println(Thread.currentThread().getName() + "
finished executing");
}
}
public class ThreadGroupDemo4
{
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting one");
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting two");
// returns the number of threads put into the array
Thread[] group = new Thread[gfg.activeCount()];
int count = gfg.enumerate(group);
for (int i = 0; i < count; i++)
{
System.out.println("Thread " + group[i].getName() + " found");
}
40
}
}
Output:
Starting one
Starting two
Thread one found
Thread two found
one finished executing
two finished executing
Example Program:
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
System.out.println(Thread.currentThread().getName() + "
finished executing");
41
}
}
public class ThreadGroupDemo5
{
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
// checking the maximum priority of parent thread
System.out.println("Maximum priority of ParentThreadGroup = "+
gfg.getMaxPriority());
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting one");
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting two");
}
}
Output:
Maximum priority of ParentThreadGroup = 10
Starting one
Starting two
two finished executing
one finished executing
Example Program:
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
42
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
System.out.println(Thread.currentThread().getName() +" finished
executing");
}
}
public class ThreadGroupDemo6
{
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
}
}
Output:
Starting one
Starting two
two finished executing
one finished executing
43
8. ThreadGroup getParent(): Returns null if the invoking
ThreadGroup object has no parent. Otherwise, it returns the
parent of the invoking object.
Syntax: final ThreadGroup getParent().
Returns: the parent of this thread group.
The top-level thread group is the only thread group whose parent
is null.
Exception: SecurityException - if the current thread cannot
modify this thread group.
Example Program:
// Java code illustrating getParent() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Exception encounterted");
}
}
System.out.println(Thread.currentThread().getName()+ " finished
executing");
}
}
44
public class ThreadGroupDemo7
{
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
// prints the parent ThreadGroup
// of both parent and child threads
System.out.println("ParentThreadGroup for " + gfg.getName()
+ " is " + gfg.getParent().getName());
System.out.println("ParentThreadGroup for " +
gfg_child.getName() + " is " + gfg_child.getParent().getName());
}
}
Output:
Starting one
Starting two
ParentThreadGroup for Parent thread is main
ParentThreadGroup for child thread is Parent thread
one finished executing
two finished executing
Example Program:
// Java code illustrating interrupt() method
45
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() +" finished
executing");
}
}
public class ThreadGroupDemo8
{
public static void main(String arg[]) throws
InterruptedException,SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
46
System.out.println("Starting " + t2.getName());
// interrupting thread group
gfg.interrupt();
}
}
Output:
Starting one
Starting two
Thread two interrupted
Thread one interrupted
one finished executing
two finished executing
Example Program:
// Java code illustrating isDaemon() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
47
catch (InterruptedException ex)
{
System.out.println("Thread" + Thread.currentThread().getName()
+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() +" finished
executing");
}
}
public class ThreadGroupDemo9
{
public static void main(String arg[]) throws InterruptedException,
SecurityException
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
if (gfg.isDaemon() == true)
System.out.println("Group is Daemon group");
else
System.out.println("Group is not Daemon group");
}
}
Output:
Starting one
Starting two
Group is not Daemon group
two finished executing
one finished executing
48
Example Program:
// Java code illustrating isDestroyed() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()
+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() + "
finished executing");
}
}
public class ThreadGroupDemo10
{
public static void main(String arg[]) throws InterruptedException,
SecurityException, Exception
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
49
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
if (gfg.isDestroyed() == true)
System.out.println("Group is destroyed");
else
System.out.println("Group is not destroyed");
}
}
Output:
Starting one
Starting two
Group is not destroyed
one finished executing
two finished executing
Example Program:
// Java code illustrating list() method.
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
50
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()
+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() +
" finished executing");
}
}
public class ThreadGroupDemo11
{
public static void main(String arg[]) throws InterruptedException,
SecurityException, Exception
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
// listing contents of parent ThreadGroup
System.out.println("\nListing parentThreadGroup: " +
gfg.getName() + ":");
// prints information about this thread group
// to the standard output
gfg.list();
}
}
Output:
Starting one
Starting two
51
Listing parentThreadGroup: Parent thread:
java.lang.ThreadGroup[name=Parent thread, maxpri=10]
Thread[one, 5, Parent thread]
Thread[two, 5, Parent thread]
java.lang.ThreadGroup[name=child thread, maxpri=10]
one finished executing
two finished executing
Example Program:
// Java code illustrating parentOf() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()+ " interrupted");
52
}
}
System.out.println(Thread.currentThread().getName() + "
finished executing");
}
}
public class ThreadGroupDemo12
{
public static void main(String arg[]) throws InterruptedException,
SecurityException, Exception
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
// checking who is parent thread
if (gfg.parentOf(gfg_child))
System.out.println(gfg.getName() + " is parent of "
+ gfg_child.getName());
}
}
Output:
Starting one
Starting two
Parent thread is parent of child thread
two finished executing
one finished executing
53
Example Program:
// Java code illustrating setDaemon() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()
+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() +
" finished executing");
}
}
public class ThreadGroupDemo13
{
public static void main(String arg[]) throws InterruptedException,
SecurityException, Exception
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
// daemon status is set to true
54
gfg.setDaemon(true);
// daemon status is set to true
gfg_child.setDaemon(true);
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
if (gfg.isDaemon() && gfg_child.isDaemon())
System.out.println("Parent Thread group and "+ "child thread
group"
+ " is daemon");
}
}
Output:
Starting one
Starting two
Parent Thread group and child thread group is daemon
one finished executing
two finished executing
Example Program
// Java code illustrating setMaxPriority() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
}
public void run()
{
for (int i = 0; i < 10; i++)
{
55
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()
+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() +
" [priority = " + Thread.currentThread().getPriority() + "]
finished executing.");
}
}
public class ThreadGroupDemo14
{
public static void main(String arg[]) throws InterruptedException,
SecurityException, Exception
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
gfg.setMaxPriority(Thread.MAX_PRIORITY - 2);
gfg_child.setMaxPriority(Thread.NORM_PRIORITY);
NewThread t1 = new NewThread("one", gfg);
t1.setPriority(Thread.MAX_PRIORITY);
System.out.println("Starting " + t1.getName());
t1.start();
NewThread t2 = new NewThread("two", gfg_child);
t2.setPriority(Thread.MAX_PRIORITY);
System.out.println("Starting " + t2.getName());
t2.start();
}
}
Output:
56
Starting one
Starting two
two [priority = 5] finished executing.
one [priority = 8] finished executing.
Example Program:
// Java code illustrating toString() method
import java.lang.*;
class NewThread extends Thread
{
NewThread(String threadname, ThreadGroup tgob)
{
super(tgob, threadname);
start();
}
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
System.out.println("Thread " +
Thread.currentThread().getName()
+ " interrupted");
}
}
System.out.println(Thread.currentThread().getName() +
" finished executing");
}
}
57
public class ThreadGroupDemo15
{
public static void main(String arg[]) throws InterruptedException,
SecurityException, Exception
{
// creating the thread group
ThreadGroup gfg = new ThreadGroup("Parent thread");
ThreadGroup gfg_child = new ThreadGroup(gfg, "child thread");
// daemon status is set to true
gfg.setDaemon(true);
// daemon status is set to true
gfg_child.setDaemon(true);
NewThread t1 = new NewThread("one", gfg);
System.out.println("Starting " + t1.getName());
NewThread t2 = new NewThread("two", gfg);
System.out.println("Starting " + t2.getName());
// string equivalent of the parent group
System.out.println("String equivalent: " + gfg.toString());
}
}
Output:
Starting one
Starting two
String equivalent: java.lang.ThreadGroup[name=Parent thread,
maxpri=10]
one finished executing
two finished executing
58
interface, or method that operates on a parameterized type is
called generic, as in generic class or generic method.
Object is the superclass of all other classes, an Object reference
can refer to any type object. Thus, in pre-generics code,
generalized classes, interfaces, and methods used Object
references to operate on various types of objects.
Java Generic methods and generic classes enable programmers
to specify, with a single method declaration, a set of related
methods, or with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows
programmers to catch invalid types at compile time.
Using Java Generic concept, we might write a generic method for
sorting an array of objects, then invoke the generic method with
Integer arrays, Double arrays, String arrays and so on, to sort
the array elements.
General Form:
class class-name<type-param-list>
{
//Body of the class
}
59
Example Program:
class Gen<T>
{
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o)
{
ob = o;
}
// Return ob.
T getob()
{
return ob;
}
// Show type of T.
void showType()
{
System.out.println("Type of T is " + ob.getClass().getName());
}
}
// Demonstrate the generic class.
class GenDemo
{
public static void main(String args[])
{
// Create a Gen reference for Integers.
Gen<Integer> iOb;
// Create a Gen<Integer> object and assign its
// reference to iOb. Notice the use of autoboxing
// to encapsulate the value 88 within an Integer object.
iOb = new Gen<Integer>(88);
// Show the type of data used by iOb.
iOb.showType();
// Get the value in iOb. Notice that
// no cast is needed.
int v = iOb.getob();
System.out.println("value: " + v);
60
System.out.println();
// Create a Gen object for Strings.
Gen<String> strOb = new Gen<String> ("Generics Test");
// Show the type of data used by strOb.
strOb.showType();
// Get the value of strOb. Again, notice
// that no cast is needed.
String str = strOb.getob();
System.out.println("value: " + str);
}
}
Output:
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test
Example Program:
// A simple generic class with two type
// parameters: T and V.
class TwoGen<T, V>
{
T ob1;
V ob2;
// Pass the constructor a reference to
// an object of type T and an object of type V.
TwoGen(T o1, V o2)
{
ob1 = o1;
ob2 = o2;
}
// Show types of T and V.
61
void showTypes()
{
System.out.println("Type of T is " +ob1.getClass().getName());
System.out.println("Type of V is " +ob2.getClass().getName());
}
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
// Demonstrate TwoGen.
class SimpGen
{
public static void main(String args[])
{
TwoGen<Integer, String> tgObj =new TwoGen<Integer,
String>(88, "Generics");
// Show the types.
tgObj.showTypes();
// Obtain and show values.
int v = tgObj.getob1();
System.out.println("value: " + v);
String str = tgObj.getob2();
System.out.println("value: " + str);
}
}
Output:
Type of T is java.lang.Integer
Type of V is java.lang.String
value: 88
value: Generics
62
2 Marks Questions and Answers
1. Difference between multitasking and multithreading.
Multithreading Multitasking
The system executes The system allows executing
multiple threads of the multiple programs and tasks
same or different at the same time
processes at the same
time.
CPU has to switch CPU has to switch between
between multiple multiple programs so that
threads to make it it appears that multiple
appear that all threads programs are running
are running simultaneously.
simultaneously
Threads belonging to the Multitasking allocates
same process shares separate memory and
the same memory and resources for each
resources as that of the process/program
process.
2. What is thread?
A thread is a lightweight sub process, a smallest unit of
processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads. It shares a common
memory area.
63
5. What is the role of Newborn State?
When we create a thread object, the thread is born and is said
to be newborn -state. In this state, we can do the following
tasks
Schedule a thread for running using start() method
Kill a thread using stop() method
64
9. Write down the role of Dead State.
Every thread has a life cycle. A running thread ends its life
when it has completed executing its run() method. It is a
natural death. We can kill it by sending the stop message to it
at any state.
67
23. Write down the purpose of using Daemon thread in
java.
It provides services to user threads for background
supporting tasks. It has no role in life than to serve user
threads.
Its life depends on user threads.
It is a low priority thread.
15 Marks Questions
1. Define thread. Explain the states of thread briefly. State the
reasons for synchronization in thread. Write a simple
concurrent programming to create, sleep, and delete the
threads.
2. State the motivations of generic programming. Explain the
generic classes and methods with example.
3. Write a Java program to display the different combinations of
20-20 cricket teams with team member names using
multithreading.
4. Write a Java program that correctly implements producer
consumer problem using the concept of inter thread
communication
5. How will you resolve deadlock in Interthread communication?
69