Skip to content

Commit c017048

Browse files
committed
[add] add some examples of concurrency
1 parent 4a04b68 commit c017048

15 files changed

+429
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
6+
/**
7+
* Created by brian on 16/11/30.
8+
*/
9+
public class CachedThreadPool {
10+
public static void main(String[] args) {
11+
ExecutorService exec = Executors.newCachedThreadPool();
12+
for (int i = 0; i < 5; i++) {
13+
exec.execute(new LiftOff());
14+
}
15+
exec.shutdown();
16+
}
17+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.ArrayList;
4+
import java.util.concurrent.Callable;
5+
import java.util.concurrent.ExecutionException;
6+
import java.util.concurrent.ExecutorService;
7+
import java.util.concurrent.Executors;
8+
import java.util.concurrent.Future;
9+
10+
/**
11+
* Created by brian on 16/11/30.
12+
*/
13+
public class CallableDemo {
14+
public static void main(String[] args) {
15+
ExecutorService exec = Executors.newCachedThreadPool();
16+
ArrayList<Future<String>> results = new ArrayList<>();
17+
18+
for (int i = 0; i < 10; i++) {
19+
results.add(exec.submit(new TaskWithResult(i)));
20+
}
21+
22+
for (Future<String> fs : results) {
23+
try {
24+
System.out.println(fs.get());
25+
} catch (InterruptedException e) {
26+
System.out.println(e);
27+
e.printStackTrace();
28+
} catch (ExecutionException e) {
29+
System.out.println(e);
30+
e.printStackTrace();
31+
} finally {
32+
exec.shutdown();
33+
}
34+
}
35+
}
36+
}
37+
38+
class TaskWithResult implements Callable<String> {
39+
private int id;
40+
41+
public TaskWithResult(int id) {
42+
this.id = id;
43+
}
44+
45+
@Override
46+
public String call() throws Exception {
47+
return "result of TaskWithResult " + id;
48+
}
49+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.ThreadFactory;
6+
7+
/**
8+
* TODO 为什么有两个线程?
9+
*/
10+
public class CaptureUncaughtException {
11+
public static void main(String[] args) {
12+
ExecutorService exec = Executors.newCachedThreadPool(
13+
new HandlerThreadFactory());
14+
exec.execute(new ExceptionThread());
15+
}
16+
}
17+
18+
class ExceptionThread implements Runnable {
19+
public void run() {
20+
Thread t = Thread.currentThread();
21+
System.out.println("run() by " + t);
22+
System.out.println(
23+
"eh = " + t.getUncaughtExceptionHandler());
24+
throw new RuntimeException();
25+
}
26+
}
27+
28+
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
29+
public void uncaughtException(Thread t, Throwable e) {
30+
System.out.println("caught " + e + " in " + t);
31+
}
32+
}
33+
34+
class HandlerThreadFactory implements ThreadFactory {
35+
public Thread newThread(Runnable r) {
36+
System.out.println(this + " creating new Thread");
37+
Thread t = new Thread(r);
38+
System.out.println("created " + t);
39+
t.setUncaughtExceptionHandler(
40+
new MyUncaughtExceptionHandler());
41+
System.out.println(
42+
"eh = " + t.getUncaughtExceptionHandler());
43+
return t;
44+
}
45+
}
46+
47+
48+
49+
/* Output: (90% match)
50+
com.brianway.learning.java.concurrent.HandlerThreadFactory@266474c2 creating new Thread
51+
created Thread[Thread-0,5,main]
52+
eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@6f94fa3e
53+
run() by Thread[Thread-0,5,main]
54+
eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@6f94fa3e
55+
com.brianway.learning.java.concurrent.HandlerThreadFactory@266474c2 creating new Thread
56+
created Thread[Thread-1,5,main]
57+
eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@3ff961b5
58+
caught java.lang.RuntimeException in Thread[Thread-0,5,main]
59+
*///:~
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.TimeUnit;
6+
7+
/**
8+
* Using a Thread Factory to create daemons.
9+
*/
10+
public class DaemonFromFactory implements Runnable {
11+
public void run() {
12+
try {
13+
while (true) {
14+
TimeUnit.MILLISECONDS.sleep(100);
15+
System.out.println(Thread.currentThread() + " " + this);
16+
}
17+
} catch (InterruptedException e) {
18+
System.out.println("Interrupted");
19+
}
20+
}
21+
22+
public static void main(String[] args) throws Exception {
23+
ExecutorService exec = Executors.newCachedThreadPool(
24+
new DaemonThreadFactory());
25+
for (int i = 0; i < 10; i++)
26+
exec.execute(new DaemonFromFactory());
27+
System.out.println("All daemons started");
28+
TimeUnit.MILLISECONDS.sleep(500); // Run for a while
29+
}
30+
} /* (Execute to see output) *///:~
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.ThreadFactory;
4+
5+
/**
6+
* Created by brian on 16/12/1.
7+
*/
8+
public class DaemonThreadFactory implements ThreadFactory {
9+
@Override
10+
public Thread newThread(Runnable r) {
11+
Thread t = new Thread(r);
12+
t.setDaemon(true);
13+
return t;
14+
}
15+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.TimeUnit;
4+
5+
/**
6+
* Daemon threads don't run the finally clause
7+
*
8+
* output:"Starting ADaemon" or nothing
9+
*/
10+
11+
public class DaemonsDontRunFinally {
12+
public static void main(String[] args) throws Exception {
13+
Thread t = new Thread(new ADaemon());
14+
t.setDaemon(true);
15+
t.start();
16+
}
17+
}
18+
19+
class ADaemon implements Runnable {
20+
public void run() {
21+
try {
22+
System.out.println("Starting ADaemon");
23+
TimeUnit.SECONDS.sleep(1);
24+
} catch (InterruptedException e) {
25+
System.out.println("Exiting via InterruptedException");
26+
} finally {
27+
System.out.println("This should always run?");
28+
}
29+
}
30+
}
31+
/* Output:
32+
Starting ADaemon
33+
34+
or
35+
36+
output nothing
37+
*///:~
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
6+
/**
7+
* Created by brian on 16/11/30.
8+
*/
9+
public class FixedThreadPool {
10+
public static void main(String[] args) {
11+
ExecutorService exec = Executors.newFixedThreadPool(5);
12+
for (int i = 0; i < 5; i++) {
13+
exec.execute(new LiftOff());
14+
}
15+
exec.shutdown();
16+
}
17+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
/**
4+
* Understanding join().
5+
*
6+
* 异常捕获时将清理标志位
7+
*/
8+
class Sleeper extends Thread {
9+
private int duration;
10+
11+
public Sleeper(String name, int sleepTime) {
12+
super(name);
13+
duration = sleepTime;
14+
start();
15+
}
16+
17+
public void run() {
18+
try {
19+
sleep(duration);
20+
} catch (InterruptedException e) {
21+
System.out.println(getName() + " was interrupted. " +
22+
"isInterrupted(): " + isInterrupted());
23+
return;
24+
}
25+
System.out.println(getName() + " has awakened");
26+
}
27+
}
28+
29+
class Joiner extends Thread {
30+
private Sleeper sleeper;
31+
32+
public Joiner(String name, Sleeper sleeper) {
33+
super(name);
34+
this.sleeper = sleeper;
35+
start();
36+
}
37+
38+
public void run() {
39+
try {
40+
sleeper.join();
41+
} catch (InterruptedException e) {
42+
System.out.println("Interrupted");
43+
}
44+
System.out.println(getName() + " join completed");
45+
}
46+
}
47+
48+
public class Joining {
49+
public static void main(String[] args) {
50+
Sleeper
51+
sleepy = new Sleeper("Sleepy", 1500),
52+
grumpy = new Sleeper("Grumpy", 1500);
53+
Joiner
54+
dopey = new Joiner("Dopey", sleepy),
55+
doc = new Joiner("Doc", grumpy);
56+
grumpy.interrupt();
57+
}
58+
}
59+
/* Output:
60+
Grumpy was interrupted. isInterrupted(): false
61+
Doc join completed
62+
Sleepy has awakened
63+
Dopey join completed
64+
*///:~
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
/**
4+
* Created by brian on 16/11/30.
5+
*/
6+
public class LiftOff implements Runnable {
7+
protected int countDown = 10;
8+
private static int taskCount = 0;
9+
private final int id = taskCount++;
10+
11+
public LiftOff() {
12+
}
13+
14+
public LiftOff(int countDown) {
15+
this.countDown = countDown;
16+
}
17+
18+
public String status() {
19+
return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + "), ";
20+
}
21+
22+
@Override
23+
public void run() {
24+
while (countDown-- > 0) {
25+
System.out.print(status());
26+
Thread.yield();
27+
}
28+
}
29+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
/**
4+
* Created by brian on 16/11/30.
5+
*/
6+
public class MoreBasicThreads {
7+
public static void main(String[] args) {
8+
for (int i = 0; i < 5; i++) {
9+
new Thread(new LiftOff()).start();
10+
}
11+
System.out.println("Waiting for LiftOff");
12+
}
13+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.brianway.learning.java.concurrent;
2+
3+
import java.util.concurrent.TimeUnit;
4+
5+
/**
6+
* Daemon threads don't prevent the program from ending.
7+
*/
8+
public class SimpleDaemons implements Runnable {
9+
public void run() {
10+
try {
11+
while (true) {
12+
TimeUnit.MILLISECONDS.sleep(100);
13+
System.out.println(Thread.currentThread() + " " + this);
14+
}
15+
} catch (InterruptedException e) {
16+
System.out.println("sleep() interrupted");
17+
}
18+
}
19+
20+
public static void main(String[] args) throws Exception {
21+
for (int i = 0; i < 10; i++) {
22+
Thread daemon = new Thread(new SimpleDaemons());
23+
daemon.setDaemon(true); // Must call before start()
24+
daemon.start();
25+
}
26+
System.out.println("All daemons started");
27+
TimeUnit.MILLISECONDS.sleep(175);
28+
}
29+
}
30+
31+
/* Output: (Sample)
32+
All daemons started
33+
Thread[Thread-8,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@1ec8f532
34+
Thread[Thread-4,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@17d10736
35+
Thread[Thread-1,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@2eec0173
36+
Thread[Thread-0,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@78f0e569
37+
Thread[Thread-5,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@572f3b73
38+
Thread[Thread-6,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@6c8d15b7
39+
Thread[Thread-2,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@31229a57
40+
Thread[Thread-3,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@4059e324
41+
Thread[Thread-9,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@32e39829
42+
Thread[Thread-7,5,main] com.brianway.learning.java.concurrent.SimpleDaemons@45401023
43+
44+
...
45+
*///:~

0 commit comments

Comments
 (0)