Skip to content

Commit fb16c19

Browse files
committed
🔖 《第1章 并发简介》示例代码
1 parent 668aebc commit fb16c19

File tree

7 files changed

+276
-151
lines changed

7 files changed

+276
-151
lines changed

codes/concurrent/src/main/java/io/github/dunwu/javase/concurrent/chapter01/ConcurrencyTest.java

Lines changed: 0 additions & 57 deletions
This file was deleted.
Lines changed: 42 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,57 @@
11
package io.github.dunwu.javase.concurrent.chapter01;
22

3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
import java.util.concurrent.TimeUnit;
7+
38
/**
4-
* 死锁例子
5-
*
6-
* @author tengfei.fangtf
7-
* @version $Id: DeadLockDemo.java, v 0.1 2015-7-18 下午10:08:28 tengfei.fangtf Exp $
9+
* 死锁示例
10+
* @see DeadLockFixDemo
811
*/
12+
@SuppressWarnings("all")
913
public class DeadLockDemo {
1014

11-
/** A锁 */
12-
private static String A = "A";
13-
/** B锁 */
14-
private static String B = "B";
15+
public static void main(String[] args) throws InterruptedException {
16+
List<Integer> list1 = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10));
17+
List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 3, 7, 9, 11));
1518

16-
public static void main(String[] args) {
17-
new DeadLockDemo().deadLock();
19+
Thread thread1 = new Thread(() -> {
20+
moveListItem(list1, list2, 2);
21+
});
22+
Thread thread2 = new Thread(() -> {
23+
moveListItem(list2, list1, 9);
24+
});
25+
26+
thread1.start();
27+
thread2.start();
28+
thread1.join();
29+
thread2.join();
30+
System.out.println(list1);
31+
System.out.println(list2);
1832
}
1933

20-
private void deadLock() {
21-
Thread t1 = new Thread(new Runnable() {
22-
@Override
23-
public void run() {
24-
synchronized (A) {
25-
try {
26-
Thread.sleep(2000);
27-
} catch (InterruptedException e) {
28-
e.printStackTrace();
29-
}
30-
synchronized (B) {
31-
System.out.println("1");
32-
}
33-
}
34+
private static void moveListItem(List<Integer> from, List<Integer> to, Integer item) {
35+
log("attempting lock for list", from);
36+
synchronized (from) {
37+
log("lock acquired for list", from);
38+
try {
39+
TimeUnit.SECONDS.sleep(1);
40+
} catch (InterruptedException e) {
41+
e.printStackTrace();
3442
}
35-
});
36-
37-
Thread t2 = new Thread(new Runnable() {
38-
@Override
39-
public void run() {
40-
synchronized (B) {
41-
synchronized (A) {
42-
System.out.println("2");
43-
}
43+
log("attempting lock for list ", to);
44+
synchronized (to) {
45+
log("lock acquired for list", to);
46+
if (from.remove(item)) {
47+
to.add(item);
4448
}
49+
log("moved item to list ", to);
4550
}
46-
});
47-
t1.start();
48-
t2.start();
51+
}
4952
}
5053

54+
private static void log(String msg, Object target) {
55+
System.out.println(Thread.currentThread().getName() + ": " + msg + " " + System.identityHashCode(target));
56+
}
5157
}

codes/concurrent/src/main/java/io/github/dunwu/javase/concurrent/lock/DeadLockFixDemo.java renamed to codes/concurrent/src/main/java/io/github/dunwu/javase/concurrent/chapter01/DeadLockFixDemo.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package io.github.dunwu.javase.concurrent.lock;
1+
package io.github.dunwu.javase.concurrent.chapter01;
22

33
import java.util.ArrayList;
44
import java.util.Arrays;
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package io.github.dunwu.javase.concurrent.chapter01;
2+
3+
/**
4+
* 活锁问题示例
5+
*/
6+
public class LivelockDemo {
7+
8+
public static void main(String[] args) {
9+
final Worker worker1 = new Worker("Worker 1 ", true);
10+
final Worker worker2 = new Worker("Worker 2", true);
11+
12+
final CommonResource s = new CommonResource(worker1);
13+
14+
new Thread(() -> {
15+
worker1.work(s, worker2);
16+
}).start();
17+
18+
new Thread(() -> {
19+
worker2.work(s, worker1);
20+
}).start();
21+
}
22+
23+
static class CommonResource {
24+
25+
private Worker owner;
26+
27+
CommonResource(Worker d) {
28+
owner = d;
29+
}
30+
31+
Worker getOwner() {
32+
return owner;
33+
}
34+
35+
synchronized void setOwner(Worker d) {
36+
owner = d;
37+
}
38+
}
39+
40+
static class Worker {
41+
42+
private String name;
43+
private boolean active;
44+
45+
Worker(String name, boolean active) {
46+
this.name = name;
47+
this.active = active;
48+
}
49+
50+
public String getName() {
51+
return name;
52+
}
53+
54+
private boolean isActive() {
55+
return active;
56+
}
57+
58+
synchronized void work(
59+
CommonResource commonResource,
60+
Worker otherWorker) {
61+
while (active) {
62+
// wait for the resource to become available.
63+
if (commonResource.getOwner() != this) {
64+
try {
65+
wait(10);
66+
} catch (InterruptedException e) {
67+
//ignore
68+
}
69+
continue;
70+
}
71+
72+
// If other worker is also active let it do it's work first
73+
if (otherWorker.isActive()) {
74+
System.out.println(getName() + " : handing over the resource to the worker: " +
75+
otherWorker.getName());
76+
commonResource.setOwner(otherWorker);
77+
continue;
78+
}
79+
80+
//now use the commonResource
81+
System.out.println(getName() + ": working on the common resource");
82+
active = false;
83+
commonResource.setOwner(otherWorker);
84+
}
85+
}
86+
}
87+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package io.github.dunwu.javase.concurrent.chapter01;
2+
3+
import java.awt.Dimension;
4+
import java.awt.FlowLayout;
5+
import javax.swing.JComponent;
6+
import javax.swing.JFrame;
7+
import javax.swing.JProgressBar;
8+
9+
/**
10+
* 饥饿问题示例
11+
*/
12+
@SuppressWarnings("all")
13+
public class StarvationDemo {
14+
15+
private static Object sharedObj = new Object();
16+
17+
public static void main(String[] args) {
18+
JFrame frame = createFrame();
19+
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
20+
21+
for (int i = 0; i < 5; i++) {
22+
ProgressThread progressThread = new ProgressThread();
23+
frame.add(progressThread.getProgressComponent());
24+
progressThread.start();
25+
}
26+
27+
frame.setLocationRelativeTo(null);
28+
frame.setVisible(true);
29+
}
30+
31+
private static JFrame createFrame() {
32+
JFrame frame = new JFrame("Starvation Demo");
33+
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
34+
frame.setSize(new Dimension(300, 200));
35+
return frame;
36+
}
37+
38+
private static class ProgressThread extends Thread {
39+
40+
JProgressBar progressBar;
41+
42+
ProgressThread() {
43+
progressBar = new JProgressBar();
44+
progressBar.setString(this.getName());
45+
progressBar.setStringPainted(true);
46+
}
47+
48+
JComponent getProgressComponent() {
49+
return progressBar;
50+
}
51+
52+
@Override
53+
public void run() {
54+
55+
int c = 0;
56+
while (true) {
57+
synchronized (sharedObj) {
58+
if (c == 100) {
59+
c = 0;
60+
}
61+
progressBar.setValue(++c);
62+
try {
63+
//sleep the thread to simulate long running task
64+
Thread.sleep(100);
65+
} catch (InterruptedException e) {
66+
e.printStackTrace();
67+
}
68+
}
69+
}
70+
}
71+
}
72+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package io.github.dunwu.javase.concurrent.chapter01;
2+
3+
import java.awt.Dimension;
4+
import java.awt.FlowLayout;
5+
import javax.swing.JComponent;
6+
import javax.swing.JFrame;
7+
import javax.swing.JProgressBar;
8+
9+
/**
10+
* 饥饿问题解决示例
11+
*/
12+
@SuppressWarnings("all")
13+
public class StarvationFixDemo {
14+
15+
private static Object sharedObj = new Object();
16+
17+
public static void main(String[] args) {
18+
JFrame frame = createFrame();
19+
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
20+
21+
for (int i = 0; i < 5; i++) {
22+
ProgressThread progressThread = new ProgressThread();
23+
frame.add(progressThread.getProgressComponent());
24+
progressThread.start();
25+
}
26+
27+
frame.setLocationRelativeTo(null);
28+
frame.setVisible(true);
29+
}
30+
31+
private static JFrame createFrame() {
32+
JFrame frame = new JFrame("Fairness Demo");
33+
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
34+
frame.setSize(new Dimension(300, 200));
35+
return frame;
36+
}
37+
38+
private static class ProgressThread extends Thread {
39+
40+
JProgressBar progressBar;
41+
42+
ProgressThread() {
43+
progressBar = new JProgressBar();
44+
progressBar.setString(this.getName());
45+
progressBar.setStringPainted(true);
46+
}
47+
48+
JComponent getProgressComponent() {
49+
return progressBar;
50+
}
51+
52+
@Override
53+
public void run() {
54+
55+
int c = 0;
56+
while (true) {
57+
synchronized (sharedObj) {
58+
if (c == 100) {
59+
c = 0;
60+
}
61+
progressBar.setValue(++c);
62+
try {
63+
//simulate long running task with wait..
64+
// releasing the lock for long running task gives
65+
//fair chances to run other threads
66+
sharedObj.wait(100);
67+
} catch (InterruptedException e) {
68+
e.printStackTrace();
69+
}
70+
}
71+
}
72+
}
73+
}
74+
}

0 commit comments

Comments
 (0)