-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNthread.java
More file actions
58 lines (47 loc) · 1.3 KB
/
Copy pathNthread.java
File metadata and controls
58 lines (47 loc) · 1.3 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
package zOther;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author dekai.kong
* @difficult
* @create 2020-07-19 15:38
* @from
**/
public class Nthread {
static int k = 100;
static Lock lock = new ReentrantLock();
static Condition[] cn = new Condition[k+1];
static class MyThread implements Runnable{
private int mod = 0;
private int total = 0;
private int k = 0;
MyThread(int total,int mod,int k){
this.mod = mod;
this.total = total;
this.k = k;
}
@Override
public void run(){
lock.lock();
while(total%k != mod){
try {
cn[mod].await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+mod);
cn[mod+1].signal();
lock.unlock();
}
}
public static void main(String[] args) {
for(int i = 0;i<cn.length;i++){
cn[i] = lock.newCondition();
}
for (int i = 1; i <= k; i++) {
new Thread(new MyThread(i,i,k)).start();
}
}
}