forked from NaNaDi/Programming_Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSampleClass.java
More file actions
93 lines (77 loc) · 2.07 KB
/
Copy pathSampleClass.java
File metadata and controls
93 lines (77 loc) · 2.07 KB
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
85
86
87
88
89
90
91
92
93
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SampleClass extends Thread{
private int sum1 = 0;
private int sum2 = 0;
Runnable runner1 = new Runnable(){
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i<5; i++){
System.out.println(Thread.currentThread().getName() + " iteration no. " + i);
}
}
};
Runnable runner2 = new Runnable(){
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i<5; i++){
System.out.println(Thread.currentThread().getName() + " iteration no. " + i);
}
}
};
public void executeRunnables(){
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(runner1);
executor.submit(runner2);
executor.shutdown();
}
public void executeThreads(){
System.out.println(Thread.currentThread().getName());
for(int i=0; i<10; i++){
new Thread("" + i){
public void run(){
System.out.println("Thread: " + getName() + " running");
}
}.start();
}
}
public void joinThreads(){
final int[] arr = {1,2,3,4,5,6};
Thread t1 = new Thread("first half"){
public void run(){
System.out.println("Thread " + Thread.currentThread().getName() + " started.");
int temp = 0;
for(int i = 0; i<=arr.length/2; i++){
temp += arr[i];
}
sum1 = temp;
}
};
Thread t2 = new Thread("second half"){
public void run(){
System.out.println("Thread " + Thread.currentThread().getName() + " started.");
int temp = 0;
for(int i = arr.length/2 + 1; i<arr.length; i++){
temp += arr[i];
}
sum2 = temp;
}
};
Thread t3 = new Thread("addition"){
public void run(){
System.out.println("Thread " + Thread.currentThread().getName() + " started.");
System.out.println("sum: " + (sum1 + sum2));
}
};
t1.start();
t2.start();
//makes sure that t3 will be executed AFTER t1 and t2 finished.
try{
t1.join();
t2.join();
} catch(InterruptedException e){
e.printStackTrace();
}
t3.start();
}
}