Thread_10_2_v1-1
Thread_10_2_v1-1
in
Java
1
Multithreading
OJECTIVE :
➢ Introduction
➢ Class Thread: An Overview of the Thread Methods
➢ Thread States: Life Cycle of a Thread
➢ Thread Priorities and Thread Scheduling
➢ Thread Synchronization
➢ Producer/Consumer Relationship without Thread Synchronization
➢ Producer/Consumer Relationship with Thread Synchronization
➢ Producer/Consumer Relationship: The Circular Buffer
➢ Daemon Threads
➢ Runnable Interface
➢ Thread Groups
2
Introduction
➢Performing operations concurrently (in parallel).
➢ A multithreaded program contains two or more parts that can run
concurrently.
➢ Each part of such a program is called a thread, and each thread defines
a separate path of execution.
➢ Thus, multithreading is a specialized form of multitasking.
3
Introduction
➢Threads of execution
➢ Each thread is a portion of a program that can execute concurrently with other
threads (multithreading)
➢This gives Java powerful capabilities not found in C and C++
➢ Example: downloading a video clip
➢Instead of having to download the entire clip then play it:
➢Download a portion, play that portion, download the next portion, play that
portion... (streaming)
➢Ensure that it is done smoothly
➢ Writing multithreaded programs is tricky
➢Imagine trying to read 3 books at once, by reading a few words at a time
4
Class Thread : An Overview of the Thread Methods
➢Overview thread-related methods
➢ Constructors
➢Thread( threadName )
➢Thread()
➢Creates an auto numbered Thread of format Thread-0, Thread-
1,Thread-2 etc...
➢ run()
➢"Does work" of thread
➢Can be overridden in a subclass of Thread or in a Runnable object .
➢ start()
➢Launches thread, then returns to caller
➢Calls run
➢Error to call start twice for same thread
5
Class Thread: An Overview of the Thread Methods
➢Thread methods
➢ static method sleep( milliseconds )
➢Thread sleeps (does not contend for processor) for number of milliseconds
➢Can give lower priority threads a chance to run
➢ interrupt
➢Interrupts a thread
➢ static method interrupted
➢Returns true if current thread interrupted
➢ isInterrupted
➢Determines if a thread is interrupted
➢ isAlive
➢Returns true if start has been called and not dead (run function has not
completed)
6
Class Thread: An Overview of the Thread Methods
➢ setName( threadName )
➢ getName()
➢ toString()
➢Returns thread name, priority, and ThreadGroup
➢ static method currentThread()
➢Returns reference to currently executing thread
➢ join()
➢Wait for a thread to terminate (Calling thread waits for the thread receiving
message to die before it can proceed)
➢No argument or 0 millisecond argument means thread will wait indefinitely
➢Can lead to deadlock/indefinite postponement
7
Thread States: Life Cycle of a Thread
➢Thread states
➢ Born state
➢Thread just created
➢When start called, enters ready state
➢ Ready state (runnable state)
➢Highest-priority ready thread enters running state
➢ Running state
➢System assigns processor to thread (thread begins execution)
➢When run method completes or terminates, enters dead state
➢ Dead state
➢Thread marked to be removed by system
➢Entered when run terminates or throws uncaught exception
8
Thread States: Life Cycle of a Thread
➢Other thread states
➢ Blocked state
➢Entered from running state
➢Blocked thread cannot use processor, even if available
➢Common reason for blocked state - waiting on I/O request
➢ Sleeping state
➢Entered when sleep method called
➢Cannot use processor
➢Enters ready state after sleep time expires
➢ Waiting state
➢Entered when wait called in an object thread is accessing
➢One waiting thread becomes ready when object calls notify
➢notifyAll - all waiting threads become ready
9
Thread Priorities and Thread Scheduling
➢ All Java applications are multithreaded
➢ Threads have priority from 1 to 10
➢ Thread.MIN_PRIORITY - 1
➢ Thread.NORM_PRIORITY - 5 (default)
➢ Thread.MAX_PRIORITY - 10
➢ New threads inherit priority of thread that created it
➢ Timeslicing
➢ Each thread gets a quantum of processor time to execute
➢ After time is up, processor given to next thread of equal priority (if available)
➢ Without timeslicing, each thread of equal priority runs to completion
10
Thread Priorities and Thread Scheduling
➢Java scheduler
➢ Keeps highest-priority thread running at all times
➢ If timeslicing available, ensure equal priority threads execute in round-
robin fashion
➢ New high priority threads could postpone execution of lower priority
threads
➢Indefinite postponement (starvation)
➢Priority methods
➢ setPriority( int priorityNumber )
➢ getPriority
➢ yield - thread yields processor to threads of equal priority
➢Useful for non-timesliced systems, where threads run to completion
11
Thread Example:
1. public class ThreadTest
2. {
3. public static void main(String arg[])throws InterruptedException
4. {
5. Thread t=new Thread();
6. Thread k=Thread.currentThread();
7. System.out.println("Current Thread:"+k+t);
8. t.setName("My Thread");
9. System.out.println("my Thread:"+t);
10. for(int i=5;i>0;i--)
11. {
12. System.out.println(i);
13. k.sleep(500);
14. }
15. }
16. } 12
Thread Example:
1. // Create a second thread by extending Thread
2. class NewThread extends Thread { 22. class ExtendThread {
3. NewThread() {
23. public static void main(String args[]) {
4. // Create a new, second thread
24. new NewThread(); // create a new thread
5. super("Demo Thread");
6. System.out.println("Child thread: " + this); 25. try {
7. start(); // Start the thread 26. for(int i = 5; i > 0; i--) {
8. } 27. System.out.println("Main Thread: " + i);
9. // This is the entry point for the second thread. 28. Thread.sleep(1000);
10. public void run() { 29. }
11. try {
30. } catch (InterruptedException e) {
12. for(int i = 5; i > 0; i--) {
31. System.out.println("Main thread
13. System.out.println("Child Thread: " + i);
interrupted.");
14. Thread.sleep(500);
15. }
32. }
16. } catch (InterruptedException e) { 33. System.out.println("Main thread exiting.");
17. System.out.println("Child interrupted."); 34. }
18. } 35. }
19. System.out.println("Exiting child thread.");
20. }
21. }
13
Thread Priorities and Thread Scheduling
➢Example program
➢ Demonstrate basic threading techniques
➢Create a class derived from Thread
➢Use sleep method
➢ Overview
➢Create four threads, which sleep for a random amount of time
➢After they finish sleeping, print their name
➢ Program has two classes
➢PrintThread
➢Derives from Thread
➢Instance variable sleepTime
➢ThreadTester
➢Creates four PrintThread objects 14
Example:
1. class PrintThread extends Thread { 21. public class ThreadTester {
2. private int sleepTime; 22. public static void main(String args[])
3. public PrintThread( String name ) 23. {
4. { 24. PrintThread thread1, thread2, thread3, thread4;
5. super( name ); 25. thread1 = new PrintThread( "thread1" );
6. sleepTime = (int) ( Math.random() * 5000 ); 26. thread2 = new PrintThread( "thread2" );
7. System.out.println( "Name: " + getName() +"; sleep: " + 27. thread3 = new PrintThread( "thread3" );
sleepTime ); 28. thread4 = new PrintThread( "thread4" );
8. }
9. public void run() 29. System.out.println( "\nStarting threads" );
10. { 30. thread1.start();
11. try { 31. thread2.start();
12. System.out.println( getName() + " going to sleep" ); 32. thread3.start();
13. Thread.sleep( sleepTime ); 33. thread4.start();
14. }
15. catch ( InterruptedException exception ) { 34. System.out.println( "Threads started\n" );
16. System.out.println( exception.toString() ); 35. }
17. } 36. }
18. System.out.println( getName() + " done sleeping" );
19. }
20. } 15
Name: thread1; sleep: 1653
Outline
Name: thread2; sleep: 2910
Name: thread3; sleep: 4436
Name: thread4; sleep: 201
Starting threads
Threads started
Starting threads
Threads started
17
Thread Synchronization
18
Producer/Consumer Relationship without Thread
Synchronization
➢ Producer / Consumer relationship
➢ Producing thread may write to buffer (shared memory)
➢ Consuming thread reads from buffer
➢ If not synchronized, data can become corrupted
➢ Producer may write before consumer read last data
➢ Data lost
➢ Consumer may read before producer writes new data
➢ Data "doubled"
➢ Using synchronization
➢ If producer knows that consumer has not read last data, calls wait (awaits a
notify command from consumer)
➢ If consumer knows producer has not updated data, calls wait (awaits notify
command from producer)
19
Producer/Consumer Relationship without
Thread Synchronization
➢ Example
➢ Producer / Consumer relationship without synchronization
➢ Overview
➢ Producer writes the numbers 1 through 10 to a buffer
➢ Consumer reads them from buffer and sums them
➢ If producer/consumer operate in order, total should be 55
➢ Classes
➢ ProduceInteger and ConsumeInteger
➢ Inherit from Thread
➢ sleep for random amount of time, then read from / write to buffer
➢ HoldIntegerUnsynchronized
➢ Has data and unsynchronized set and get methods
➢ SharedCell
➢ Driver, creates threads and calls start
20
1 // SharedCell.java Outline
2 // Show multiple threads modifying shared object.
3 public class SharedCell { Class SharedCell
7 new HoldIntegerUnsynchronized();
8 ProduceInteger p = new ProduceInteger( h );
9 ConsumeInteger c = new ConsumeInteger( h );
10
11 p.start();
12 c.start();
13 }
14 }
15
21
16 // ProduceInteger.java Outline
17 // Definition of threaded class ProduceInteger
18 public class ProduceInteger extends Thread {
19 private HoldIntegerUnsynchronized pHold;
20 Class ProduceInteger
21 public ProduceInteger( HoldIntegerUnsynchronized h )
22 {
23 super( "ProduceInteger" ); 1. extends Thread
24 pHold = h; pHold refers to a
25 }
26
HoldIntegerUnsynchronized object,
1.1 Instance variable
27 public void run() and will use its set methods.
28 {
29 for ( int count = 1; count <= 10; count++ ) { 2. run
30 // sleep for a random interval
31 try {
32 Thread.sleep( (int) ( Math.random() * 3000 ) );
2.1 Randomize sleep
33 }
34 catch( InterruptedException e ) {
2.2 setSharedInt
35 System.out.println( e.toString() );
36 }
37
38 pHold.setSharedInt( count );
39 }
40
41 System.out.println( getName() +
42 " finished producing values" +
43 "\nTerminating " + getName() );
44 }
45 }
46 22
47 // ConsumeInteger.java
48 // Definition of threaded class ConsumeInteger Outline
49 public class ConsumeInteger extends Thread {
50 private HoldIntegerUnsynchronized cHold;
51
52 public ConsumeInteger( HoldIntegerUnsynchronized h ) Class ConsumeInteger
53 {
54 super( "ConsumeInteger" );
55 cHold = h; 1. extends Thread
56 }
57
58 public void run() 1.1 Instance variable
59 {
60 int val, sum = 0;
61 2. run
62 do {
63 // sleep for a random interval
64 try { 2.1 Randomize sleep
65 Thread.sleep( (int) ( Math.random() * 3000 ) );
66 }
67 catch( InterruptedException e ) { 2.2 getSharedInt
68 System.out.println( e.toString() );
69 }
70
71 val = cHold.getSharedInt();
72 sum += val;
73 } while ( val != 10 );
74
75 System.out.println(
76 getName() + " retrieved values totaling: " + sum +
77 "\nTerminating " + getName() );
78 }
79 } 23
1 // HoldIntegerUnsynchronized.java Outline
2 // Definition of class HoldIntegerUnsynchronized
8 System.out.println( Thread.currentThread().getName() +
2. setSharedInt
9 " setting sharedInt to " + val ); (unsynchronized)
10 sharedInt = val;
11 } 3. getSharedInt
12
(unsynchronized)
13 public int getSharedInt()
14 {
15 System.out.println( Thread.currentThread().getName() +
17 return sharedInt;
18 }
19 }
24
ConsumeInteger retrieving sharedInt value -1 Outline
ConsumeInteger retrieving sharedInt value -1
ProduceInteger setting sharedInt to 1
ProduceInteger setting sharedInt to 2
ConsumeInteger retrieving sharedInt value 2 Program Output
ProduceInteger setting sharedInt to 3
ProduceInteger setting sharedInt to 4
ProduceInteger setting sharedInt to 5
ConsumeInteger retrieving sharedInt value 5
ProduceInteger setting sharedInt to 6
ProduceInteger setting sharedInt to 7
ProduceInteger setting sharedInt to 8
ConsumeInteger retrieving sharedInt value 8
ConsumeInteger retrieving sharedInt value 8
ProduceInteger setting sharedInt to 9
ConsumeInteger retrieving sharedInt value 9
ConsumeInteger retrieving sharedInt value 9
ProduceInteger setting sharedInt to 10
ProduceInteger finished producing values
Terminating ProduceInteger
ConsumeInteger retrieving sharedInt value 10
ConsumeInteger retrieved values totaling: 49
Terminating ConsumeInteger
Notice how the producer and consumer act out of
order, which results in a sum of 49 (not 55).
25
Producer/Consumer Relationship with Thread
Synchronization
➢ Condition variable of a monitor
➢ Variable used to test some condition
➢ Determines if thread should call wait
➢ For our producer / consumer relationship
➢ Condition variable determines whether the producer should write to buffer or if
consumer should read from buffer
➢ Use boolean variable writeable
➢ If writeable true, producer can write to buffer
➢ If false, then producer calls wait, and awaits notify
➢ If writeable false, consumer can read from buffer
➢ If true, consumer calls wait
26
Producer/Consumer Relationship with Thread
Synchronization
➢ Redo example program with synchronization
➢ Synchronize the set and get methods
➢ Once the producer writes to memory, writeable is false (cannot write again)
➢ Once consumer reads, writeable is true (cannot read again)
➢ Each thread relies on the other to toggle writeable and call notify
➢ Only Class HoldIntegerUnsynchronized is changed
➢ Now called HoldIntegerSynchronized
➢ We only changed the implementation of the set and get methods
27
1 // HoldIntegerSynchronized.java Outline
2 // Definition of class HoldIntegerSynchronized that
3 // uses thread synchronization to ensure that both
4 // threads access sharedInt at the proper times.
5 public class HoldIntegerSynchronized { Classes SharedCell,
6 private int sharedInt = -1; ConsumeInteger, and
7 private boolean writeable = true; // condition variable
Test the condition variable. If it is not the producer's ProduceInteger same as before
8
turn, then wait. -------------------------
9 public synchronized void setSharedInt( int val )
10 { Class HoldInteger
11 while ( !writeable ) { // not the producer's turn Synchronized
12 try {
13 wait();
1. Instance variables
14 }
15 catch ( InterruptedException e ) {
16 e.printStackTrace(); 2. setSharedInt
17 } (synchronized)
18 }
19
20 System.out.println( Thread.currentThread().getName() +
21 " setting sharedInt to " + val );
If writeable is true, write to
22 sharedInt = val;
the buffer, toggle writeable,
23
24 writeable = false;
and notify any waiting threads
25 notify(); // tell a waiting thread to (so they
become may read from the
ready
26 } buffer).
27
28
Outline
28 public synchronized int getSharedInt()
29 {
30 while ( writeable ) { // not the consumer's turn
31 try { 3.
getSharedInt
32 wait(); (synchronized)
33 }
34 catch ( InterruptedException e ) {
35 e.printStackTrace();
36 }
37 }
38
39 writeable = true;
40 notify(); // tell a waiting thread to become ready
41
42 System.err.println( Thread.currentThread().getName() +
43 " retrieving sharedInt value " + sharedInt );
44 return sharedInt;
45 }
46 }
29
ProduceInteger setting sharedInt to 1 Outline
ConsumeInteger retrieving sharedInt value 1
ProduceInteger setting sharedInt to 2
ConsumeInteger retrieving sharedInt value 2
Program Output
ProduceInteger setting sharedInt to 3
ConsumeInteger retrieving sharedInt value 3
ProduceInteger setting sharedInt to 4
ConsumeInteger retrieving sharedInt value 4
ProduceInteger setting sharedInt to 5
ConsumeInteger retrieving sharedInt value 5
ProduceInteger setting sharedInt to 6
ConsumeInteger retrieving sharedInt value 6
ProduceInteger setting sharedInt to 7
ConsumeInteger retrieving sharedInt value 7
ProduceInteger setting sharedInt to 8
ConsumeInteger retrieving sharedInt value 8
ProduceInteger setting sharedInt to 9
ConsumeInteger retrieving sharedInt value 9 The producer and consumer act in order, and the
ProduceInteger setting sharedInt to 10 proper total is reached (55).
ProduceInteger finished producing values
Terminating ProduceInteger
ConsumeInteger retrieving sharedInt value 10
ConsumeInteger retrieved values totaling: 55
Terminating ConsumeInteger
30
Producer/Consumer Relationship: The Circular Buffer
➢ Previous program
➢ Does access data properly, but not optimally
➢ Producer cannot produce faster than consumer can consume
➢ To allow this, use a circular buffer
➢ Has enough cells to handle "extra" production
➢ Once producer knows consumer has read data, allowed to overwrite it
➢ Redo program with a circular buffer
➢ For the circular buffer, use a 5-element array
➢ Have variables readLoc and writeLoc to keep track of where in array producer
and consumer are
➢ Incremented, and kept between 0 and 4 with % 5
➢ Condition variables readable and writeable
31
Producer/Consumer Relationship: The Circular Buffer
32
1 // SharedCell.java Outline
2 // Show multiple threads modifying shared object.
3 import java.text.DecimalFormat;
4 import java.awt.*;
Class SharedCell
5 import java.awt.event.*;
6 import javax.swing.*;
7 1. GUI added
8 public class SharedCell extends JFrame {
9 public SharedCell()
10 {
11 super( "Demonstrating Thread Synchronization" );
12 JTextArea output = new JTextArea( 20, 30 );
13
14 getContentPane().add( new JScrollPane( output )
);
15 setSize( 500, 500 );
16 show();
17
18 // set up threads and start threads
19 HoldIntegerSynchronized h =
20 new HoldIntegerSynchronized( output );
21 ProduceInteger p = new ProduceInteger( h, output
);
22 ConsumeInteger c = new ConsumeInteger( h, output
);
23
24 p.start();
25 c.start();
26 }
27 33
28 public static void main( String args[] ) Outline
29 {
30 SharedCell app = new SharedCell(); 1. GUI added
31 app.addWindowListener(
32 new WindowAdapter() {
33 public void windowClosing( WindowEvent e )
34 {
35 System.exit( 0 );
36 }
37 }
38 );
39 }
40}
41
34
42 // ProduceInteger.java
43 // Definition of threaded class ProduceInteger Outline
44 import javax.swing.JTextArea;
45
46 public class ProduceInteger extends Thread {
47 private HoldIntegerSynchronized pHold; Class ProduceInteger
48 private JTextArea output;
49
50 1. Instance variable added to
51 public ProduceInteger( HoldIntegerSynchronized h, accommodate GUI
52 JTextArea o )
53 {
54 super( "ProduceInteger" );
55 pHold = h;
56 output = o;
57 }
58
59 public void run()
60 {
61 for ( int count = 1; count <= 10; count++ ) {
62 // sleep for a random interval
63 // Note: Interval shortened purposely to fill buffer
64 try {
65 Thread.sleep( (int) ( Math.random() * 500 ) );
66 }
67 catch( InterruptedException e ) {
68 System.err.println( e.toString() );
69 }
70
71 pHold.setSharedInt( count );
72 } 35
Outline
73
74 output.append( "\n" + getName() + 1.1 Update GUI
75 " finished producing values" +
76 "\nTerminating " + getName() + "\n" );
77 }
78}
79
36
80 // ConsumeInteger.java
81 // Definition of threaded class ConsumeInteger
Outline
82 import javax.swing.JTextArea;
83
84 public class ConsumeInteger extends Thread {
85 private HoldIntegerSynchronized cHold; Class ConsumeInteger
86 private JTextArea output;
87
88 public ConsumeInteger( HoldIntegerSynchronized h,
1. Instance variable added to
89 JTextArea o ) accomodate GUI
90 {
91 super( "ConsumeInteger" );
92 cHold = h;
93 output = o;
94 }
95
96 public void run()
97 {
98 int val, sum = 0;
99
100 do {
101 // sleep for a random interval
102 try {
103 Thread.sleep( (int) ( Math.random() * 3000 ) );
104 }
105 catch( InterruptedException e ) {
106 System.err.println( e.toString() );
107 }
108
109 val = cHold.getSharedInt();
110 sum += val;
111 } while ( val != 10 ); 37
112 Outline
113 output.append( "\n" + getName() +
114 " retrieved values totaling: " + sum + 1.1 Update GUI
115 "\nTerminating " + getName() + "\n" );
116 }
117 }
118
38
119 // HoldIntegerSynchronized.java
120 // Definition of class HoldIntegerSynchronized that Outline
121 // uses thread synchronization to ensure that both
122 // threads access sharedInt at the proper times.
123 import javax.swing.JTextArea;
124 import java.text.DecimalFormat; Class HoldInteger
125 Synchronized
126 public class HoldIntegerSynchronized {
127 private int sharedInt[] = { -1, -1, -1, -1, -1 };
128 private boolean writeable = true;
1. Instance variables
129 private boolean readable = false;
130 private int readLoc = 0, writeLoc = 0; 2. setSharedInt
131 private JTextArea output;
132
133 public HoldIntegerSynchronized( JTextArea o )
134 {
135 output = o;
136 }
137
138 public synchronized void setSharedInt( int val )
139 {
140 while ( !writeable ) {
141 try {
142 output.append( " WAITING TO PRODUCE " + val );
143 wait();
144 }
145 catch ( InterruptedException e ) {
146 System.err.println( e.toString() );
147 }
148 }
39
149
150 sharedInt[ writeLoc ] = val;
151 readable = true; Outline
152
153 output.append( "\nProduced " + val +
154 " into cell " + writeLoc );
155 2. setSharedInt
156 writeLoc = ( writeLoc + 1 ) % 5; Set appropriate location in the
157 circular buffer. Update
158 output.append( "\twrite " + writeLoc + readable. 3. getSharedInt
159 "\tread " + readLoc);
160 displayBuffer( output, sharedInt ); Increment writeLoc, use % 5
161 to keep it in range.
162 if ( writeLoc == readLoc ) {
163 writeable = false; Test for full buffer.
164 output.append( "\nBUFFER FULL" );
165 }
166
167 notify();
168 }
169
170 public synchronized int getSharedInt()
171 {
172 int val;
173
174 while ( !readable ) {
175 try {
176 output.append( " WAITING TO CONSUME" );
177 wait();
178 }
179 catch ( InterruptedException e ) {
180 System.err.println( e.toString() );
181 }
182 } 40
183
184 writeable = true; Outline
185 val = sharedInt[ readLoc ];
186
187 output.append( "\nConsumed " + val +
188 " from cell " + readLoc ); 3. getSharedInt
189
190 readLoc = ( readLoc + 1 ) % 5;
191 4. GUI method
192 output.append( "\twrite " + writeLoc +
193 "\tread " + readLoc );
194 displayBuffer( output, sharedInt );
195
196 if ( readLoc == writeLoc ) {
197 readable = false;
198 output.append( "\nBUFFER EMPTY" );
199 }
200
201 notify();
202
203 return val;
204 }
205
206 public void displayBuffer( JTextArea out, int buf[] )
207 {
208 DecimalFormat formatNumber = new DecimalFormat( " #;-#" );
209 output.append( "\tbuffer: " );
210
211 for ( int i = 0; i < buf.length; i++ )
212 out.append( " " + formatNumber.format( buf[ i ] ));
213 }
214 } 41
Outline
Program Output
42
Daemon Threads
➢ Daemon threads
➢ Thread that runs for benefit of other threads
➢ Garbage collector
➢ Run in background
➢ Use processor time that would otherwise go to waste
➢ Unlike normal threads, do not prevent a program from terminating
➢ When only daemon threads remain, program exits
➢ Must designate a thread as daemon before start called
setDaemon( true );
➢ Method isDaemon
➢ Returns true if thread is a daemon thread
43
Runnable Interface
➢ Java does not support multiple inheritance
➢ Instead, use interfaces
➢ Until now, inherited from class Thread, override run
➢ Multithreading for an already derived class
➢ Implement interface Runnable (java.lang)
➢ New class objects "are" Runnable objects
➢ Override run method
➢ Controls thread, just as deriving from Thread class
➢ In fact, class Thread implements interface Runnable
➢ Create new threads using Thread constructors
➢ Thread( runnableObject )
➢ Thread( runnableObject, threadName )
44
Multiple Thread example:
1. // Create multiple threads.
2. class NewThread implements Runnable { 24.class MultiThreadDemo {
3. String name; // name of thread 25.public static void main(String args[]) {
4. Thread t;
26.new NewThread("One"); // start threads
5. NewThread(String threadname) {
6. name = threadname; 27.new NewThread("Two");
7. t = new Thread(this, name);
28.new NewThread("Three");
8. System.out.println("New thread: " + t);
9. t.start(); // Start the thread 29.try {
10. } 30.// wait for other threads to end
11. // This is the entry point for thread.
12. public void run() { 31.Thread.sleep(10000);
13. try { 32.} catch (InterruptedException e) {
14. for(int i = 5; i > 0; i--) {
33.System.out.println("Main thread
15. System.out.println(name + ": " + i);
Interrupted");
16. Thread.sleep(1000);
17. } 34.}
18. } catch (InterruptedException e) {
35.System.out.println("Main thread exiting.");
19. System.out.println(name + "Interrupted");
20. } 36.}
21. System.out.println(name + " exiting."); 37.}
22. }
23. }
45
Thread Groups
➢ Thread groups
➢ Threads in a thread group can be dealt with as a group
➢ May want to interrupt all threads in a group
➢ Thread group can be parent to a child thread group
➢ Class ThreadGroup
➢ Constructors
ThreadGroup( threadGroupName )
ThreadGroup( parentThreadGroup, name )
➢ Creates child ThreadGroup named name
46
Thread Groups
47
Thread Groups
➢ ThreadGroup Methods
➢ activeCount
➢ Number of active threads in a group and all child groups
➢ enumerate
➢ Two versions copy active threads into an array of references
➢ Two versions copy active threads in a child group into an array of references
➢ getMaxPriority
➢ Returns maximum priority of a ThreadGroup
➢ setMaxPriority
➢ getName, getParent
48