Skip to content

Commit c9cba5b

Browse files
committed
📝 add concurrent code example
1 parent 6217d1e commit c9cba5b

File tree

9 files changed

+368
-0
lines changed

9 files changed

+368
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.TimeUnit;
6+
import java.util.concurrent.atomic.AtomicInteger;
7+
import java.util.stream.IntStream;
8+
9+
/**
10+
* 原子变量
11+
* <p>
12+
* AtomicInteger
13+
* LongAdder
14+
* LongAccumulator
15+
*
16+
* @author biezhi
17+
* @date 2018/3/5
18+
*/
19+
public class AtomicExample {
20+
21+
public static void main(String[] args) {
22+
AtomicInteger atomicInt = new AtomicInteger(0);
23+
ExecutorService executor = Executors.newFixedThreadPool(2);
24+
IntStream.range(0, 1000)
25+
.forEach(i -> executor.submit(atomicInt::incrementAndGet));
26+
stop(executor);
27+
System.out.println(atomicInt.get());
28+
}
29+
30+
public static void stop(ExecutorService executor) {
31+
try {
32+
System.out.println("attempt to shutdown executor");
33+
executor.shutdown();
34+
executor.awaitTermination(5, TimeUnit.SECONDS);
35+
} catch (InterruptedException e) {
36+
System.err.println("tasks interrupted");
37+
} finally {
38+
if (!executor.isTerminated()) {
39+
System.err.println("cancel non-finished tasks");
40+
}
41+
executor.shutdownNow();
42+
System.out.println("shutdown finished");
43+
}
44+
}
45+
46+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.*;
4+
5+
/**
6+
* Callable Future
7+
*
8+
* @author biezhi
9+
* @date 2018/3/5
10+
*/
11+
public class CallableExample {
12+
13+
public static void main(String[] args) throws ExecutionException, InterruptedException {
14+
Callable<Integer> task = () -> {
15+
try {
16+
TimeUnit.MINUTES.sleep(1);
17+
return 123;
18+
} catch (InterruptedException e) {
19+
throw new IllegalStateException("task interrupted", e);
20+
}
21+
};
22+
23+
ExecutorService executor = Executors.newFixedThreadPool(1);
24+
Future<Integer> future = executor.submit(task);
25+
System.out.println("future done? " + future.isDone());
26+
Integer result = future.get();
27+
System.out.println("future done? " + future.isDone());
28+
System.out.print("result: " + result);
29+
30+
}
31+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.ConcurrentHashMap;
4+
import java.util.concurrent.ConcurrentMap;
5+
6+
/**
7+
* ConcurrentMap
8+
* <p>
9+
* forEach
10+
* putIfAbsent
11+
* getOrDefault
12+
* replaceAll
13+
* compute
14+
* merge
15+
* search
16+
* reduce
17+
*
18+
* @author biezhi
19+
* @date 2018/3/5
20+
*/
21+
public class ConcurrentMapExample {
22+
23+
public static void main(String[] args) {
24+
ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
25+
map.put("foo", "bar");
26+
map.put("han", "solo");
27+
map.put("r2", "d2");
28+
map.put("c3", "p0");
29+
30+
map.forEach((key, value) -> System.out.printf("%s = %s\n", key, value));
31+
32+
}
33+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
6+
/**
7+
* 执行器
8+
*
9+
* @author biezhi
10+
* @date 2018/3/5
11+
*/
12+
public class ExecutorExample {
13+
14+
public static void main(String[] args) {
15+
ExecutorService executor = Executors.newSingleThreadExecutor();
16+
executor.submit(() -> {
17+
String threadName = Thread.currentThread().getName();
18+
System.out.println("Hello " + threadName);
19+
});
20+
}
21+
22+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.TimeUnit;
6+
import java.util.concurrent.locks.ReentrantLock;
7+
8+
import static java.lang.Thread.sleep;
9+
10+
/**
11+
* 锁
12+
* <p>
13+
* ReentrantLock
14+
* ReadWriteLock
15+
* StampedLock
16+
*
17+
* @author biezhi
18+
* @date 2018/3/5
19+
*/
20+
public class LockExample {
21+
22+
ReentrantLock lock = new ReentrantLock();
23+
24+
int count = 0;
25+
26+
private void increment() {
27+
lock.lock();
28+
try {
29+
count++;
30+
} finally {
31+
lock.unlock();
32+
}
33+
}
34+
35+
public void start() {
36+
ExecutorService executor = Executors.newFixedThreadPool(2);
37+
executor.submit(() -> {
38+
lock.lock();
39+
try {
40+
sleep(1);
41+
} catch (InterruptedException e) {
42+
e.printStackTrace();
43+
} finally {
44+
lock.unlock();
45+
}
46+
});
47+
executor.submit(() -> {
48+
System.out.println("Locked: " + lock.isLocked());
49+
System.out.println("Held by me: " + lock.isHeldByCurrentThread());
50+
boolean locked = lock.tryLock();
51+
System.out.println("Lock acquired: " + locked);
52+
});
53+
stop(executor);
54+
}
55+
56+
public static void main(String[] args) {
57+
new LockExample().start();
58+
}
59+
60+
public void stop(ExecutorService executor) {
61+
try {
62+
System.out.println("attempt to shutdown executor");
63+
executor.shutdown();
64+
executor.awaitTermination(5, TimeUnit.SECONDS);
65+
} catch (InterruptedException e) {
66+
System.err.println("tasks interrupted");
67+
} finally {
68+
if (!executor.isTerminated()) {
69+
System.err.println("cancel non-finished tasks");
70+
}
71+
executor.shutdownNow();
72+
System.out.println("shutdown finished");
73+
}
74+
}
75+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.Executors;
4+
import java.util.concurrent.ScheduledExecutorService;
5+
import java.util.concurrent.ScheduledFuture;
6+
import java.util.concurrent.TimeUnit;
7+
8+
/**
9+
* ScheduledExecutor
10+
*
11+
* @author biezhi
12+
* @date 2018/3/5
13+
*/
14+
public class ScheduledExecutorExample {
15+
16+
public static void main(String[] args) throws InterruptedException {
17+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
18+
Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
19+
ScheduledFuture<?> future = executor.schedule(task, 3, TimeUnit.SECONDS);
20+
TimeUnit.MILLISECONDS.sleep(1337);
21+
long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
22+
System.out.printf("剩余延迟: %sms", remainingDelay);
23+
}
24+
25+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.Semaphore;
6+
import java.util.concurrent.TimeUnit;
7+
import java.util.stream.IntStream;
8+
9+
import static java.lang.Thread.sleep;
10+
11+
/**
12+
* 信号量
13+
* <p>
14+
* Semaphore
15+
*
16+
* @author biezhi
17+
* @date 2018/3/5
18+
*/
19+
public class SemaphoreExample {
20+
21+
public static void main(String[] args) {
22+
ExecutorService executor = Executors.newFixedThreadPool(10);
23+
Semaphore semaphore = new Semaphore(5);
24+
Runnable longRunningTask = () -> {
25+
boolean permit = false;
26+
try {
27+
permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
28+
if (permit) {
29+
System.out.println("Semaphore acquired");
30+
sleep(5);
31+
} else {
32+
System.out.println("Could not acquire semaphore");
33+
}
34+
} catch (InterruptedException e) {
35+
throw new IllegalStateException(e);
36+
} finally {
37+
if (permit) {
38+
semaphore.release();
39+
}
40+
}
41+
};
42+
43+
IntStream.range(0, 10)
44+
.forEach(i -> executor.submit(longRunningTask));
45+
stop(executor);
46+
}
47+
48+
public static void stop(ExecutorService executor) {
49+
try {
50+
System.out.println("attempt to shutdown executor");
51+
executor.shutdown();
52+
executor.awaitTermination(5, TimeUnit.SECONDS);
53+
} catch (InterruptedException e) {
54+
System.err.println("tasks interrupted");
55+
} finally {
56+
if (!executor.isTerminated()) {
57+
System.err.println("cancel non-finished tasks");
58+
}
59+
executor.shutdownNow();
60+
System.out.println("shutdown finished");
61+
}
62+
}
63+
64+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.TimeUnit;
6+
import java.util.stream.IntStream;
7+
8+
/**
9+
* 同步
10+
*
11+
* @author biezhi
12+
* @date 2018/3/5
13+
*/
14+
public class SynchronizeExample {
15+
16+
int count = 0;
17+
18+
private void increment() {
19+
count = count + 1;
20+
}
21+
22+
public void start() {
23+
ExecutorService executor = Executors.newFixedThreadPool(2);
24+
IntStream.range(0, 10000)
25+
.forEach(i -> executor.submit(this::increment));
26+
stop(executor);
27+
System.out.println(count); // 9965
28+
}
29+
30+
public static void main(String[] args) {
31+
new SynchronizeExample().start();
32+
}
33+
34+
public void stop(ExecutorService executor) {
35+
try {
36+
System.out.println("attempt to shutdown executor");
37+
executor.shutdown();
38+
executor.awaitTermination(5, TimeUnit.SECONDS);
39+
} catch (InterruptedException e) {
40+
System.err.println("tasks interrupted");
41+
} finally {
42+
if (!executor.isTerminated()) {
43+
System.err.println("cancel non-finished tasks");
44+
}
45+
executor.shutdownNow();
46+
System.out.println("shutdown finished");
47+
}
48+
}
49+
50+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package io.github.biezhi.java8.concurrent;
2+
3+
/**
4+
* 线程
5+
*
6+
* @author biezhi
7+
* @date 2018/3/5
8+
*/
9+
public class ThreadExample {
10+
11+
public static void main(String[] args) {
12+
Runnable task = () -> {
13+
String threadName = Thread.currentThread().getName();
14+
System.out.println("Hello " + threadName);
15+
};
16+
task.run();
17+
Thread thread = new Thread(task);
18+
thread.start();
19+
System.out.println("Done!");
20+
}
21+
22+
}

0 commit comments

Comments
 (0)