编程-域名反转功能

编程-域名反转功能

题目描述

  • 实现两个线程交替打印1-100

代码实现

1. Condition 版本

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
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 资源类
// 等待 业务 通知
class Data2{
private int number = 0;

Lock lock = new ReentrantLock();

// Condition取代了对象监视器
Condition condition = lock.newCondition();

// + 1
public void increment() throws InterruptedException {
lock.lock();

try {
while (number %2 != 0){
// 等待操作
condition.await();
}
number ++;
System.out.println(Thread.currentThread().getName()+"--->"+number);
// 通知线程 + 1完毕
condition.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}



public void increment2() throws InterruptedException {
lock.lock();

try {
while (number % 2 == 0){
// 等待操作
condition.await();
}
number ++;
System.out.println(Thread.currentThread().getName()+"--->"+number);
// 通知线程 + 1完毕
condition.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
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
public class B {
public static void main(String[] args) {

Data2 data2 = new Data2();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data2.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data2.increment2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信