Collections.synchronizd***:把不加锁 的加锁。
java.util.concurrent
ConCurrentHashMap():高并发
ConcurrentSkipListMap():高并发还排序
Queue分两种,一种是ConcurrentLinkedQueue,一种是BlockingQueue.
ConcurrentLinkedQueue():Queue不能装空值,offer()加入元素,poll()是拿出元素后删掉,peek()是拿出不删掉,
LinkedBlockingQueue():阻塞式队列,无界队列,put()满了就会等待,take()如果空了就等待。
ArrayBLockingQueue():有界队列,如果队列满了,offer不会报异常,只返回加入成功与否,add会报异常。
DelayQueue():无界队列,默认排好顺序。
LinkedTransferQueue():先检测有没有消费者,有就不往队列里放。transfer()会阻塞,put,offer不会阻塞。
SynchronusQueue():容量为0的队列,来的消息必须马上消费,只能调用put(),会阻塞等待消费者消费;不能用add()
线程池:
Executor:execute(Runnable command);//不需要返回值,用来执行某一任务
public interface Executor { void execute(Runnable command); }
ExecutorService extends Executor ;//一个服务,等待任务,
public interface ExecutorService extends Executor { ... }
Callable:
public interface Callable<V>{//需要返回值时用这个 V call() throws Exception; }
Executors:工厂类
/*Factory and utility methods for {@link Executor}, {@link
* ExecutorService}, {@link ScheduledExecutorService}, {@link
* ThreadFactory}, and {@link Callable} classes defined in this
* package. This class supports the following kinds of methods:
*/
public class Executors { ... }
ThreadPool:
Future:FutureTask,
public interface Future<V> { ... }
WorkStealingPool:精灵线程,守护线程
ForkJoin:
Arrays.stream(num).sum();//累加。
public class test { static int[] nums = new int[1000000]; static final int MAX_NUM = 50000; static Random r = new Random(); static { for(int i =0 ;i<nums.length;i++){ nums[i] = r.nextInt(100); } System.out.println(Arrays.stream(nums).sum()); }
//RecursiveAction没有返回值
//RecursiveTask有返回值
// static class AddTask extends RecursiveTask<Long>{ static class AddTask extends RecursiveAction{ int start,end; AddTask(int s,int e){ start = s; end = e; } @Override protected void compute() { if(end - start <= MAX_NUM){ long sum = 0l; for(int i = start;i<end;i++)sum+=nums[i]; System.out.println("from:"+start+" to:"+end+" = "+sum);
//return sum; }else { int middle = start+(end-start)/2; AddTask subTask1 = new AddTask(start,middle); AddTask subTask2 = new AddTask(middle,end); subTask1.fork(); subTask2.fork();
//return subTask1.join()+subTask2.join(); } } } public static void main(String[] args) throws IOException { ForkJoinPool fjp = new ForkJoinPool(); AddTask task = new AddTask(0,nums.length); fjp.execute(task); //long result = task.join();RecursiveTask时放开 //System.out.println(result); System.in.read(); }}
ParallelStream:
List<Integer> nums = new ArrayList<>(); nums.parallelStream().forEach(调用的方法);