Threads - The Thread Class
BasicThread bt = new BasicThread('!');
BasicThread bt1 = new BasicThread('*');
bt.start();
bt1.start();
- the start() method allocates system resources required for a thread, schedules the thread to run and invokes the run() method
- the above code will execute but nothing will happen
- if you want your thread to do something you need to override the run() method
- the run() method is actually defined in the Runnable interface which the class Thread implements
public void run() {
for(int i=0; i<100; i++) {
System.out.print(c);
}
}
- if the above code is added and the threads started you see something like:
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*
!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!****
***********************************************
- the output is intermingled because the threads are running concurrently and are interleaved
- you can alter thread processing with program control mechanisms
- one way is to use the sleep() method which is defined in the Thread class
- the sleep() method stops the execution of a thread for a given number of milliseconds
- it also throws an InterruptedException so you need to wrap it in a try-catch block
- adding sleep() to the run method can alter the threads execution
| Note |
- the sleep() method uses a timed wait() but does not tie up the current object's lock (for information on locks see Synchronization)
|
New run() method:
public void run() {
for(int i=0; i<100; i++) {
System.out.print(c);
try{
sleep((int)(Math.random() * 10));
} catch( InterruptedException e ) {
System.out.println("Interrupted");
}
}
}
Example output:
*!*!!*!*!**!!!*!!*!***!*!!***!*!*!*!*!!!!***!!*!*
!!*!**!*!!*!**!*!**!!*!**!!*!!*!*!**!*!***!!!!*!*
!!*!**!*!*!*!*!*!*!*!!*!*!*!!!*!*!!!*!*!!*!*!*!*!
!*!**!*!*!**!**!!*!***!!!****!*!!****!*!**!!**!!!
****
0 Thread-0
0 Thread-1
1 Thread-0
1 Thread-1
2 Thread-0
2 Thread-1
3 Thread-0
3 Thread-1
4 Thread-1
4 Thread-0
DONE! Thread-0
DONE! Thread-1
ThreadGroup
- you can group threads using the ThreadGroup class
- this allows multiple threads to be handled as one unit ie for setting priority, destroying, etc
- threads in the same group can access information about other threads in the group but not about the parent thread or threads in other groups
- a ThreadGroup can have both daemon and nondaemon threads
Example Code
|