java 并发
java 并发
New
Runnable
CPU
Running Ready
Blocking
Waiting
CPU
Timed Waiting
Thread.sleep() “ ”
Object.wait() “ ”
Thread.sleep() Object.wait()
Thread.sleep()
Timeout Object.wait() / Object.notify() / Object.notifyAll()
Timeout Thread.join() /
LockSupport.parkNanos() -
LockSupport.parkUntil() -
Terminated
Runnable
Callable
Thread
Runnable
run()
Thread start()
java public class MyRunnable implements Runnable { public void run() { // ... } }
java public static void main(String[] args) { MyRunnable instance = new MyRunnable(); Thread thread = new
Thread(instance); thread.start(); }
Callable
Runnable Callable FutureTask
java public class MyCallable implements Callable<Integer> { public Integer call() { return 123; } }
java public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable mc = new
MyCallable(); FutureTask<Integer> ft = new FutureTask<>(mc); Thread thread = new Thread(ft); thread.start();
System.out.println(ft.get()); }
Thread
run() Thread Runable
start() run()
java public class MyThread extends Thread { public void run() { // ... } }
java public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); }
VS Thread
Java Thread
Thread
Executor
Executor
Executor
CachedThreadPool
FixedThreadPool
SingleThreadExecutor 1 FixedThreadPool
java public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int
i = 0; i < 5; i++) { executorService.execute(new MyRunnable()); } executorService.shutdown(); }
Daemon
main()
setDaemon()
java public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.setDaemon(true); }
sleep()
Thread.sleep(millisec) millisec
yield()
Thread.yield()
InterruptedException
interrupt() InterruptedException
I/O synchronized
} ```
java public static void main(String[] args) throws InterruptedException { Thread thread1 = new MyThread1();
thread1.start(); thread1.interrupt(); System.out.println("Main run"); }
interrupted()
run() sleep() InterruptedException interrupt()
} ```
java public static void main(String[] args) throws InterruptedException { Thread thread2 = new MyThread2();
thread2.start(); thread2.interrupt(); }
Executor
Executor shutdown() shutdownNow() interrupt()
Lambda
synchronized
1.
ExecutorService
} ```
java public static void main(String[] args) { SynchronizedExample e1 = new SynchronizedExample(); ExecutorService
executorService = Executors.newCachedThreadPool(); executorService.execute(() -> e1.func1()); executorService.execute(()
-> e1.func1()); }
html 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
java public static void main(String[] args) { SynchronizedExample e1 = new SynchronizedExample(); SynchronizedExample e2
= new SynchronizedExample(); ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func1()); executorService.execute(() -> e2.func1()); }
html 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
2.
3.
} ```
java public static void main(String[] args) { SynchronizedExample e1 = new SynchronizedExample(); SynchronizedExample e2
= new SynchronizedExample(); ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func2()); executorService.execute(() -> e2.func2()); }
html 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
4.
ReentrantLock
ReentrantLock java.util.concurrent J.U.C
} ```
java public static void main(String[] args) { LockExample lockExample = new LockExample(); ExecutorService
executorService = Executors.newCachedThreadPool(); executorService.execute(() -> lockExample.func());
executorService.execute(() -> lockExample.func()); }
html 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
1.
2.
3.
ReentrantLock synchronized
4.
synchronized ReentrantLock
5.
ReentrantLock Condition
b b a join() b a a
b
private A a;
B(A a) {
this.a = a;
}
@Override
public void run() {
try {
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}
}
} ```
java public static void main(String[] args) { JoinExample example = new JoinExample(); example.test(); }
A
B
Object Thread
IllegalMonitorStateException
wait() notify()
notifyAll()
wait() sleep()
wait() await()
Lock Condition
} ```
J.U.C - AQS
java.util.concurrent J.U.C AQS J.U.C
CountdownLatch
} ```
html run..run..run..run..run..run..run..run..run..run..end
CyclicBarrier
```java public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count =
parties; this.barrierCommand = barrierAction; }
} ```
html
before..before..before..before..before..before..before..before..before..before..after..after..after..after..after..after..after..after..after..a
Semaphore
Semaphore
3 10
} ```
html 2 1 2 2 2 2 2 1 2 2
J.U.C -
FutureTask
Callable Future FutureTask RunnableFuture Runnable Future
FutureTask
FutureTask FutureTask
} ```
BlockingQueue
java.util.concurrent.BlockingQueue
BlockingQueue
@Override
public void run() {
try {
String product = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("consume..");
}
}
} ```
java public static void main(String[] args) { for (int i = 0; i < 2; i++) { Producer producer = new Producer();
producer.start(); } for (int i = 0; i < 5; i++) { Consumer consumer = new Consumer(); consumer.start(); } for (int i = 0;
i < 3; i++) { Producer producer = new Producer(); producer.start(); } }
html produce..produce..consume..consume..produce..consume..produce..consume..produce..consume..
ForkJoin
MapReduce
@Override
protected Integer compute() {
int result = 0;
if (last - first <= threshold) {
// 任务⾜足够⼩小则直接计算
for (int i = first; i <= last; i++) {
result += i;
}
} else {
// 拆分成⼩小任务
int middle = first + (last - first) / 2;
ForkJoinExample leftTask = new ForkJoinExample(first, middle);
ForkJoinExample rightTask = new ForkJoinExample(middle + 1, last);
leftTask.fork();
rightTask.fork();
result = leftTask.join() + rightTask.join();
}
return result;
}
} ```
java public static void main(String[] args) throws ExecutionException, InterruptedException { ForkJoinExample example =
new ForkJoinExample(1, 10000); ForkJoinPool forkJoinPool = new ForkJoinPool(); Future result =
forkJoinPool.submit(example); System.out.println(result.get()); }
ForkJoinPool CPU
Thread2 Thread1
Task1 Thread1 Task2
1000 cnt 1000
} ```
java public static void main(String[] args) throws InterruptedException { final int threadSize = 1000;
ThreadUnsafeExample example = new ThreadUnsafeExample(); final CountDownLatch countDownLatch = new
CountDownLatch(threadSize); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i <
threadSize; i++) { executorService.execute(() -> { example.add(); countDownLatch.countDown(); }); }
countDownLatch.await(); executorService.shutdown(); System.out.println(example.get()); }
html 997
Java
Java Java
Java 8
read
load read read
use
assign
store
write store store
lock
unlock
1.
Java read load use assign store write lock unlock int assign
Java volatile 64 long double 32
load store read write
AtomicInteger
} ```
java public static void main(String[] args) throws InterruptedException { final int threadSize = 1000; AtomicExample
example = new AtomicExample(); // 只修改这条语句 final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < threadSize; i++) {
executorService.execute(() -> { example.add(); countDownLatch.countDown(); }); } countDownLatch.await();
executorService.shutdown(); System.out.println(example.get()); }
html 1000
} ```
java public static void main(String[] args) throws InterruptedException { final int threadSize = 1000;
AtomicSynchronizedExample example = new AtomicSynchronizedExample(); final CountDownLatch countDownLatch = new
CountDownLatch(threadSize); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i <
threadSize; i++) { executorService.execute(() -> { example.add(); countDownLatch.countDown(); }); }
countDownLatch.await(); executorService.shutdown(); System.out.println(example.get()); }
html 1000
2.
Java
volatile
synchronized unlock
final final this this
final
3.
Java
volatile
synchronized
1.
unlock lock
3. volatile
volatile
4.
Thread start()
5.
Thread join()
6.
interrupt() interrupted()
7.
“ Finalizer Rule
finalize()
8.
“ Transitivity
A B B C A C
Immutable
final
String
Collections.unmodifiableXXX()
java public class ImmutableExample { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>();
Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(map); unmodifiableMap.put("a", 1); } }
Collections.unmodifiableXXX()
1. CAS
2. AtomicInteger
J.U.C AtomicInteger Unsafe CAS
AtomicInteger
getAndAddInt()
```java public final int getAndAddInt(Object var1, long var2, int var4) { int var5; do { var5 = this.getIntVolatile(var1, var2); }
while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
} ```
3. ABA
A B A CAS
1.
java public class StackClosedExample { public void add100() { int cnt = 0; for (int i = 0; i < 100; i++) { cnt++; }
System.out.println(cnt); } }
java public static void main(String[] args) { StackClosedExample example = new StackClosedExample(); ExecutorService
executorService = Executors.newCachedThreadPool(); executorService.execute(() -> example.add100());
executorService.execute(() -> example.add100()); executorService.shutdown(); }
“ - ”
Web “ ” Thread-per-Request
Web
java.lang.ThreadLocal
java public class ThreadLocalExample { public static void main(String[] args) { ThreadLocal threadLocal = new
ThreadLocal(); Thread thread1 = new Thread(() -> { threadLocal.set(1); try { Thread.sleep(1000); } catch
(InterruptedException e) { e.printStackTrace(); } System.out.println(threadLocal.get()); threadLocal.remove(); }); Thread
thread2 = new Thread(() -> { threadLocal.set(2); threadLocal.remove(); }); thread1.start(); thread2.start(); } }
html 1
ThreadLocal
java public class ThreadLocalExample1 { public static void main(String[] args) { ThreadLocal threadLocal1 = new
ThreadLocal(); ThreadLocal threadLocal2 = new ThreadLocal(); Thread thread1 = new Thread(() -> { threadLocal1.set(1);
threadLocal2.set(1); }); Thread thread2 = new Thread(() -> { threadLocal1.set(2); threadLocal2.set(2); });
thread1.start(); thread2.start(); } }
Thread ThreadLocal.ThreadLocalMap
java /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
java public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null)
map.set(this, value); else createMap(t, value); }
get()
java public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value;
return result; } } return setInitialValue(); }
ThreadLocal
( ) ThreadLocal.ThreadLocalMap ThreadLocal
ThreadLocal remove() ThreadLocal
3. Reentrant Code
Pure Code
JVM synchronized
CPU
JDK 1.6
java public static String concatString(String s1, String s2, String s3) { return s1 + s2 + s3; }
java public static String concatString(String s1, String s2, String s3) { StringBuffer sb = new StringBuffer();
sb.append(s1); sb.append(s2); sb.append(s3); return sb.toString(); }
append() sb concatString() sb
concatString()
append()
append() append()
CAS
CAS CAS
CAS
Revoke Bias
Bug
synchronized
BlockingQueue
ConcurrentHashMap Hashtable
Java Top 50
BlockingQueue
thread state java
CSC 456 Spring 2012/ch7 MN
Java - Understanding Happens-before relationship
6 Thread Synchronization
How is Java's ThreadLocal implemented under the hood?
Concurrent
JAVA FORK JOIN EXAMPLE
——Fork/Join
Eliminating SynchronizationRelated Atomic Operations with Biased Locking and Bulk Rebiasing