-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathTaskThreadDemo.java
81 lines (72 loc) · 1.7 KB
/
TaskThreadDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package chapter_thirty_two.samples;
/**
* Listing 32.1 TaskThreadDemo.java
* */
public class TaskThreadDemo
{
public static void main(String[] args)
{
// Create tasks
Runnable printA = new PrintChar('a', 100);
Runnable printB = new PrintChar('b', 100);
Runnable print100 = new PrintNum(100);
// Create threads
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
// Start threads
thread1.start();
thread2.start();
thread3.start();
}
}
// The task for printing a character a specified number of times
class PrintChar implements Runnable
{
private char charToPrint; // The character to print
private int times; // The number of times to repeat
/**
* Construct a task with a specified character and number of
* times to print the character
*/
public PrintChar(char c, int t)
{
charToPrint = c;
times = t;
}
/**
* Override the run() method to tell the system
* what task to perform
*/
@Override
public void run()
{
for (int i = 0; i < times; i++)
{
System.out.print(charToPrint);
}
}
}
// The task class for printing numbers from 1 to n for a given n
class PrintNum implements Runnable
{
private int lastNum;
/**
* Construct a task for printing 1, 2, ..., n
*/
public PrintNum(int n)
{
lastNum = n;
}
/**
* Tell the thread how to run
*/
@Override
public void run()
{
for (int i = 1; i <= lastNum; i++)
{
System.out.print(" " + i);
}
}
}