0% found this document useful (0 votes)
10 views24 pages

java 并发

Uploaded by

li123400
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views24 pages

java 并发

Uploaded by

li123400
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

I* * New * Runnable * Blocking * Waiting * Timed Waiting *

Terminated * * Runnable * Callable * Thread * VS Thread * * Executor *


Daemon * sleep() * yield() * * InterruptedException * interrupted() * Executor * * synchronized * ReentrantLock *
* * * join() * wait() notify() notifyAll() * await() signal() signalAll() * J.U.C - AQS * CountdownLatch * CyclicBarrier *
Semaphore * J.U.C - * FutureTask * BlockingQueue * ForkJoin * * Java * *
* * * * * * * * * * * *
* * *

New

Runnable
CPU

Running Ready

Blocking

Waiting
CPU

Timeout Object.wait() Object.notify() / Object.notifyAll()


Timeout Thread.join()
LockSupport.park() -

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 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

sleep() InterruptedException main()

java public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }

yield()
Thread.yield()

java public void run() { Thread.yield(); }

InterruptedException
interrupt() InterruptedException
I/O synchronized

main() Thread.sleep() InterruptedException

```java public class InterruptExample {

private static class MyThread1 extends Thread {


@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

} ```

java public static void main(String[] args) throws InterruptedException { Thread thread1 = new MyThread1();
thread1.start(); thread1.interrupt(); System.out.println("Main run"); }

html Main run java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at


InterruptExample.lambda$main$0(InterruptExample.java:5) at InterruptExample$$Lambda$1/713338599.run(Unknown Source) at
java.lang.Thread.run(Thread.java:745)

interrupted()
run() sleep() InterruptedException interrupt()

interrupt() interrupted() true interrupted()

```java public class InterruptExample {

private static class MyThread2 extends Thread {


@Override
public void run() {
while (!interrupted()) {
// ..
}
System.out.println("Thread end");
}
}

} ```
java public static void main(String[] args) throws InterruptedException { Thread thread2 = new MyThread2();
thread2.start(); thread2.interrupt(); }

html Thread end

Executor
Executor shutdown() shutdownNow() interrupt()

Lambda

java public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool();


executorService.execute(() -> { try { Thread.sleep(2000); System.out.println("Thread run"); } catch (InterruptedException
e) { e.printStackTrace(); } }); executorService.shutdownNow(); System.out.println("Main run"); }

html Main run java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at


ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9) at
ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)

Executor submit() Future<?> cancel(true)

java Future<?> future = executorService.submit(() -> { // .. }); future.cancel(true);

Java JVM synchronized JDK ReentrantLock

synchronized
1.

java public void func() { synchronized (this) { // ... } }

ExecutorService

```java public class SynchronizedExample {

public void func1() {


synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
}
}

} ```

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.

java public synchronized void func () { // ... }

3.

java public void func() { synchronized (SynchronizedExample.class) { // ... } }

```java public class SynchronizedExample {


public void func2() {
synchronized (SynchronizedExample.class) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
}
}

} ```

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.

java public synchronized static void fun() { // ... }

ReentrantLock
ReentrantLock java.util.concurrent J.U.C

```java public class LockExample {

private Lock lock = new ReentrantLock();

public void func() {


lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
} finally {
lock.unlock(); // 确保释放锁,从⽽而避免发⽣生死锁。
}
}

} ```

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.

synchronized JVM ReentrantLock JDK

2.

Java synchronized synchronized ReentrantLock

3.

ReentrantLock synchronized

4.

synchronized ReentrantLock

5.

ReentrantLock Condition

ReentrantLock synchronized synchronized JVM JVM


ReentrantLock JDK synchronized JVM
join()
join()

b b a join() b a a
b

```java public class JoinExample {

private class A extends Thread {


@Override
public void run() {
System.out.println("A");
}
}

private class B extends Thread {

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");
}
}

public void test() {


A a = new A();
B b = new B(a);
b.start();
a.start();
}

} ```

java public static void main(String[] args) { JoinExample example = new JoinExample(); example.test(); }

A
B

wait() notify() notifyAll()


wait() notify() notifyAll()

Object Thread

IllegalMonitorStateException

wait() notify()
notifyAll()

```java public class WaitNotifyExample {

public synchronized void before() {


System.out.println("before");
notifyAll();
}

public synchronized void after() {


try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after");
}
} ```

java public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool();


WaitNotifyExample example = new WaitNotifyExample(); executorService.execute(() -> example.after());
executorService.execute(() -> example.before()); }

html before after

wait() sleep()

wait() Object sleep() Thread


wait() sleep()

await() signal() signalAll()


java.util.concurrent Condition Condition await() signal()
signalAll()

wait() await()

Lock Condition

```java public class AwaitSignalExample {

private Lock lock = new ReentrantLock();


private Condition condition = lock.newCondition();

public void before() {


lock.lock();
try {
System.out.println("before");
condition.signalAll();
} finally {
lock.unlock();
}
}

public void after() {


lock.lock();
try {
condition.await();
System.out.println("after");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

} ```

java public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool();


AwaitSignalExample example = new AwaitSignalExample(); executorService.execute(() -> example.after());
executorService.execute(() -> example.before()); }

html before after

J.U.C - AQS
java.util.concurrent J.U.C AQS J.U.C

CountdownLatch

cnt countDown() 1 0 await()


```java public class CountdownLatchExample {

public static void main(String[] args) throws InterruptedException {


final int totalThread = 10;
CountDownLatch countDownLatch = new CountDownLatch(totalThread);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalThread; i++) {
executorService.execute(() -> {
System.out.print("run..");
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println("end");
executorService.shutdown();
}

} ```

html run..run..run..run..run..run..run..run..run..run..end

CyclicBarrier

CountdownLatch await() 1 0 await()

CyclicBarrier CountdownLatch CyclicBarrier reset()

CyclicBarrier parties barrierAction

```java public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count =
parties; this.barrierCommand = barrierAction; }

public CyclicBarrier(int parties) { this(parties, null); } ```


```java public class CyclicBarrierExample {

public static void main(String[] args) {


final int totalThread = 10;
CyclicBarrier cyclicBarrier = new CyclicBarrier(totalThread);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalThread; i++) {
executorService.execute(() -> {
System.out.print("before..");
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.print("after..");
});
}
executorService.shutdown();
}

} ```

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

```java public class SemaphoreExample {

public static void main(String[] args) {


final int clientCount = 3;
final int totalRequestCount = 10;
Semaphore semaphore = new Semaphore(clientCount);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalRequestCount; i++) {
executorService.execute(()->{
try {
semaphore.acquire();
System.out.print(semaphore.availablePermits() + " ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
});
}
executorService.shutdown();
}

} ```

html 2 1 2 2 2 2 2 1 2 2

J.U.C -
FutureTask
Callable Future FutureTask RunnableFuture Runnable Future
FutureTask

java public class FutureTask<V> implements RunnableFuture<V>

java public interface RunnableFuture<V> extends Runnable, Future<V>

FutureTask FutureTask

```java public class FutureTaskExample {


public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int result = 0;
for (int i = 0; i < 100; i++) {
Thread.sleep(10);
result += i;
}
return result;
}
});

Thread computeThread = new Thread(futureTask);


computeThread.start();

Thread otherThread = new Thread(() -> {


System.out.println("other task is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
otherThread.start();
System.out.println(futureTask.get());
}

} ```

html other task is running... 4950

BlockingQueue
java.util.concurrent.BlockingQueue

FIFO LinkedBlockingQueue ArrayBlockingQueue


PriorityBlockingQueue

take() put() take() put()

BlockingQueue

```java public class ProducerConsumer {

private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);

private static class Producer extends Thread {


@Override
public void run() {
try {
queue.put("product");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("produce..");
}
}

private static class Consumer extends Thread {

@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

```java public class ForkJoinExample extends RecursiveTask {

private final int threshold = 5;


private int first;
private int last;

public ForkJoinExample(int first, int last) {


this.first = first;
this.last = last;
}

@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()); }

ForkJoin ForkJoinPool CPU

java public class ForkJoinPool extends AbstractExecutorService

ForkJoinPool CPU
Thread2 Thread1
Task1 Thread1 Task2
1000 cnt 1000

```java public class ThreadUnsafeExample {

private int cnt = 0;

public void add() {


cnt++;
}

public int get() {


return cnt;
}

} ```

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

int cnt int 1000


997 1000

3 load assign store

cnt load assign store T1 cnt


T2 cnt 1 2 int
load assign store
AtomicInteger

AtomicInteger

```java public class AtomicExample { private AtomicInteger cnt = new AtomicInteger();


public void add() {
cnt.incrementAndGet();
}

public int get() {


return cnt.get();
}

} ```

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

synchronized lock unlock


monitorenter monitorexit

```java public class AtomicSynchronizedExample { private int cnt = 0;

public synchronized void add() {


cnt++;
}

public synchronized int get() {


return cnt;
}

} ```

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

cnt volatile volatile

3.
Java

volatile

synchronized

volatile synchronized JVM

1.

“ Single Thread rule


2.

“ Monitor Lock Rule

unlock lock

3. volatile

“ Volatile Variable Rule

volatile
4.

“ Thread Start Rule

Thread start()

5.

“ Thread Join Rule

Thread join()
6.

“ Thread Interruption Rule

interrupt() interrupted()

7.

“ Finalizer Rule

finalize()

8.

“ Transitivity

A B B C A C

Immutable

final
String

Number Long Double BigInteger BigDecimal Number AtomicInteger


AtomicLong

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); } }

html Exception in thread "main" java.lang.UnsupportedOperationException at


java.util.Collections$UnmodifiableMap.put(Collections.java:1457) at ImmutableExample.main(ImmutableExample.java:9)

Collections.unmodifiableXXX()

java public V put(K key, V value) { throw new UnsupportedOperationException(); }


synchronized ReentrantLock

1. CAS

Compare-and-Swap CAS CAS 3 V A B V


A V B

2. AtomicInteger
J.U.C AtomicInteger Unsafe CAS

AtomicInteger

```java private AtomicInteger cnt = new AtomicInteger();

public void add() { cnt.incrementAndGet(); } ```

incrementAndGet() Unsafe getAndAddInt()

java public final int incrementAndGet() { return unsafe.getAndAddInt(this, valueOffset, 1) + 1; }

getAndAddInt() var1 var2 var4 1


getIntVolatile(var1, var2) compareAndSwapInt() CAS var5
var1+var2 var5+var4

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

J.U.C AtomicStampedReference CAS


ABA ABA

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(); }

html 100 100

2. Thread Local Storage

“ - ”
Web “ ” Thread-per-Request
Web

java.lang.ThreadLocal

thread1 threadLocal 1 thread2 threadLocal 2 thread1 threadLocal 1


thread2

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;

ThreadLocal set(T value) ThreadLocalMap ThreadLocal->value Map

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; }

String String JDK 1.5 StringBuffer append()

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()

JDK 1.6 unlocked biasble lightweight locked


inflated

HotSpot Mark Word tag bits state


marked for gc

Lock Record Mark Word


Mark Word

CAS
CAS CAS

0 01 unlocked Lock Record


CAS Mark Word Lock Record CAS Mark Word
00
CAS Mark Word

CAS

1 01 CAS ID Mark Word CAS

Revoke Bias

Bug

synchronized

wait() notify() CountDownLatch, CyclicBarrier, Semaphore Exchanger wait()


notify() JDK

BlockingQueue

ConcurrentHashMap Hashtable

BruceEckel. Java : 4 [M]. , 2007.


. Java [M]. , 2011.
Threads and Locks

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

You might also like