Java Reference
In-Depth Information
L ISTING 30.1
TaskThreadDemo.java
1 public class TaskThreadDemo {
2 public static void main(String[] args) {
3 // Create tasks
4 Runnable printA = new PrintChar( 'a' , 100 );
5 Runnable printB = new PrintChar( 'b' , 100 );
6 Runnable print100 = new PrintNum( 100 );
7
8 // Create threads
9 Thread thread1 = new Thread(printA);
10 Thread thread2 = new Thread(printB);
11 Thread thread3 = new Thread(print100);
12
13 // Start threads
14 thread1.start();
15 thread2.start();
16 thread3.start();
17 }
18 }
19
20 // The task for printing a character a specified number of times
21 class PrintChar implements Runnable {
22
create tasks
create threads
start threads
task class
private char charToPrint; // The character to print
23
private int times; // The number of times to repeat
24
25 /** Construct a task with a specified character and number of
26 * times to print the character
27 */
28 public PrintChar( char c, int t) {
29 charToPrint = c;
30 times = t;
31 }
32
33 @Override /** Override the run() method to tell the system
34 * what task to perform
35 */
36 public void run() {
37 for ( int i = 0 ; i < times; i++) {
38 System.out.print(charToPrint);
39 }
40 }
41 }
42
43 // The task class for printing numbers from 1 to n for a given n
44 class PrintNum implements Runnable {
45
run
task class
private int lastNum;
46
47 /** Construct a task for printing 1, 2, ..., n */
48 public PrintNum( int n) {
49 lastNum = n;
50 }
51
52 @Override /** Tell the thread how to run */
53 public void run() {
54 for ( int i = 1 ; i <= lastNum; i++) {
55 System.out.print( " " + i);
56 }
57 }
58 }
run
 
 
Search WWH ::




Custom Search