-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcounter.java
84 lines (76 loc) · 1.89 KB
/
counter.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
82
83
84
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author evivehealth on 08/02/19.
*/
// Java program depicting
// concurrent programming in action.
// Runnable Class that defines the logic
// of run method of runnable interface
public class Counter implements Runnable
{
private final MainApp mainApp;
private final int loopLimit;
private final String task;
// Constructor to get a reference to the main class
public Counter
(MainApp mainApp, int loopLimit, String task)
{
this.mainApp = mainApp;
this.loopLimit = loopLimit;
this.task = task;
}
// Prints the thread name, task number and
// the value of counter
// Calls pause method to allow multithreading to occur
@Override
public void run()
{
for (int i = 0; i < loopLimit; i++)
{
System.out.println("Thread: " +
Thread.currentThread().getName() + " Counter: "
+ (i + 1) + " Task: " + task);
mainApp.pause(Math.random());
}
}
}
class MainApp
{
// Starts the threads. Pool size 2 means at any time
// there can only be two simultaneous threads
public void startThread()
{
ExecutorService taskList =
Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++)
{
// Makes tasks available for execution.
// At the appropriate time, calls run
// method of runnable interface
taskList.execute(new Counter(this, i + 1,
"task " + (i + 1)));
}
// Shuts the thread that's watching to see if
// you have added new tasks.
taskList.shutdown();
}
// Pauses execution for a moment
// so that system switches back and forth
public void pause(double seconds)
{
try
{
Thread.sleep(Math.round(1000.0 * seconds));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// Driver method
public static void main(String[] args)
{
new MainApp().startThread();
}
}