首页 Java 并发
文章
取消

Java 并发

Concurrency 并发

Synchronized 语句块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package synchronizing;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SheepManager {
	
	private int sheepCount = 0;
	
	// private void incrementAndReport() {
	private void incrementAndReport() {
		synchronized(this) {
        System.out.print((++sheepCount)+" ");
        }
	}

	public static void main(String[] args) {

		ExecutorService service = null;
		try {
			service = Executors.newFixedThreadPool(20);
			
			SheepManager manager = new SheepManager();
			for(int i = 0; i < 10; i++) 
				service.submit(()-> manager.incrementAndReport());
			} finally {
				if (service != null) service.shutdown();
			}
	}
}

使用 Monitor 或称为 Lock,使用 synchronized 的时候,注意🔒的对象是那个。保证同步,就要去要锁同一个对象。

并发集合类

类名称接口元素有序?可排序?阻塞?
ConcurrentHashMapConcurrentMapNoNoNo
ConcurrentLinkedDequeDequeYesNoNo
ConcurrentLinkedQueueQueueYesNoNo
ConcurrentSkipListMapConcurrentMap, SortedMap, NavigableMapYesYesNo
ConcurrentSkipListSetSortedSet, NavigableSetYesYesNo
CopyOnWriteArrayListListYesNoNo
CopyOnWriteArraySetSetYesNoNo
LinkedBlockingDequeBlockingQueue, BlockingDequeYesNoYes
LinkedBlockingQueueBlockingQueueYesNoYes

Understanding CopyOnWrite Collections

1
2
3
4
5
6
7
List<Integer> list = new CopyOnWriteArrayList<>(Arrays.asList(4,3,52));
for (Integer item: list) {
	System.out.print(item+" ");
	list.add(9);
}
System.out.println();
System.out.println("Size: "+list.size());
本文由作者按照 CC BY 4.0 进行授权