Skip to content

Commit 38a5751

Browse files
committed
✨ 两个线程交替执行
1 parent 2d25ea3 commit 38a5751

File tree

2 files changed

+116
-1
lines changed

2 files changed

+116
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
- [ConcurrentHashMap 的实现原理](https://github.com/crossoverJie/Java-Interview/blob/master/MD/ConcurrentHashMap.md)
1515
- [线程池原理](https://github.com/crossoverJie/Java-Interview/blob/master/MD/ThreadPoolExecutor.md)
1616
- [线程间通信](https://github.com/crossoverJie/Java-Interview/blob/master/src/main/java/com/crossoverjie/actual/ThreadCommunication.java)
17-
17+
- 交替打印奇偶数
1818

1919
### Java 底层
2020
- [Java 运行时内存划分](https://github.com/crossoverJie/Java-Interview/blob/master/MD/MemoryAllocation.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
package com.crossoverjie.actual;
2+
3+
import java.util.concurrent.locks.Lock;
4+
import java.util.concurrent.locks.ReentrantLock;
5+
6+
/**
7+
* Function: 两个线程交替执行打印 1~100
8+
*
9+
* @author crossoverJie
10+
* Date: 11/02/2018 10:04
11+
* @since JDK 1.8
12+
*/
13+
public class TwoThread {
14+
15+
private int start = 1 ;
16+
17+
/**
18+
* 保证内存可见性
19+
* 其实用锁了之后也可以保证可见性 这里用不用 volatile 都一样
20+
*/
21+
private boolean flag = false ;
22+
23+
/**
24+
* 重入锁
25+
*/
26+
private final static Lock LOCK = new ReentrantLock() ;
27+
28+
public static void main(String[] args) {
29+
TwoThread twoThread = new TwoThread() ;
30+
31+
Thread t1 = new Thread(new OuNum(twoThread));
32+
t1.setName("t1");
33+
34+
35+
Thread t2 = new Thread(new JiNum(twoThread)) ;
36+
t2.setName("t2");
37+
38+
t1.start();
39+
t2.start();
40+
}
41+
42+
/**
43+
* 偶数线程
44+
*/
45+
public static class OuNum implements Runnable{
46+
47+
private TwoThread number ;
48+
49+
public OuNum(TwoThread number) {
50+
this.number = number;
51+
}
52+
53+
@Override
54+
public void run() {
55+
while (number.start <= 100){
56+
57+
if (number.flag){
58+
try {
59+
LOCK.lock();
60+
System.out.println(Thread.currentThread().getName() + "+-+" + number.start);
61+
number.start++;
62+
number.flag = false;
63+
64+
65+
}finally {
66+
LOCK.unlock();
67+
}
68+
}else {
69+
try {
70+
Thread.sleep(10);
71+
} catch (InterruptedException e) {
72+
e.printStackTrace();
73+
}
74+
}
75+
}
76+
}
77+
}
78+
79+
/**
80+
* 奇数线程
81+
*/
82+
public static class JiNum implements Runnable{
83+
84+
private TwoThread number ;
85+
86+
public JiNum(TwoThread number) {
87+
this.number = number;
88+
}
89+
90+
@Override
91+
public void run() {
92+
while (number.start <= 100){
93+
94+
if (!number.flag){
95+
try {
96+
LOCK.lock();
97+
System.out.println( Thread.currentThread().getName() + "+-+" + number.start);
98+
number.start++;
99+
number.flag = true;
100+
101+
102+
}finally {
103+
LOCK.unlock();
104+
}
105+
}else {
106+
try {
107+
Thread.sleep(10);
108+
} catch (InterruptedException e) {
109+
e.printStackTrace();
110+
}
111+
}
112+
}
113+
}
114+
}
115+
}

0 commit comments

Comments
 (0)