并发编程

  • 线程池:线程的创建和销毁时间大于执行时间

http://blog.csdn.net/hsuxu/article/details/8985931
executor框架:http://www.cnblogs.com/MOBIN/p/5436482.html
将提交任务的线程和执行任务的线程解耦,采用生产者消费者模式。
并用Runnable来表示任务。
executors:提供一系列静态工厂方法来创建线程池。
newFixedThreadPool:创建固定数量的线程池
newScheduledThreadPool:创建可延时执行或定时执行的线程池
newCachedThreadPool:再一定时间内未使用的线程会被移除,有之前创建的可用线程就重用,否则新建。
线程池使用举例:

public class ThreadPoolDemo {
     
    static class Task implements Runnable{
        private String id;
        Task(String id){
            this.id = id;
        }
        @Override
        public void run() {
            System.out.println("Thread "+id+" is working"); 
            try {
                //每个任务随机延时1s以内的时间以模拟线程的运行
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread "+id+" over");
        }
    }
public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);//线程池中,3工作线程
        threadPool.execute(new Task("a"));
        threadPool.execute(new Task("b"));
        threadPool.execute(new Task("c"));
        threadPool.execute(new Task("d"));
        threadPool.execute(new Task("e"));
        threadPool.shutdown();
        while(!threadPool.isTerminated()){
        }
        System.out.println("Thread Pool is over");
    }
}
  • concurrenthashmap

http://blog.csdn.net/yansong_8686/article/details/50664351

并发编程_第1张图片
image.png
  • volidate关键字

线程栈(线程的工作内存)保存了线程运行时候变量值信息。当线程访问某一个对象时候值的时候,首先通过对象的引用找到对应在堆内存的变量的值,然后把堆内存变量的具体值load到线程本地内存中,建立一个变量副本,之后线程就不再和对象在堆内存变量值有任何关系,而是直接修改副本变量的值,在修改完之后的某一个时刻(线程退出之前),自动把线程变量本的值回写到对象在堆中变量。这样在堆中的对象的值就产生变化了。

并发编程_第2张图片
image.png
  • 关于REENTRANTLOCK和SYNCHRONIZED

http://blog.csdn.net/fw0124/article/details/6672522

你可能感兴趣的:(并发编程)