并发(不太懂)

笔记:

concurrence:
    1、同步访问共享的可变数据
        关键字synchronized可以保证在同一时刻,只有一个线程可以执行某一个方法。同步不仅仅是一种互斥的方式,还可以保证进入同步方法或者同步代码块的每个线程都看到由一个锁保护之前所有的修改结果。
        不要使用Thread.stop
        当多个线程共享可变数据的时候,每个读写和数据的线程都必须执行同步。如果只需要线程之间的交互通信,而不需要互斥,volatile修饰符就是一种可以接受的同步形式。
    2、避免过度同步
        为了避免活性失败和安全性失败,在一个呗同步的方法或者代码块中,永远不要放弃对客户端的控制。换句话说,在一个被同步的区域内部,不要调用设计成要被覆盖的方法,或者是由客户端以函数对象形式提供的方法。
    3、executor和task优先于线程
    4、并发工具优先于wait和notify
    5、线程安全性的文档化
    6、慎用延迟初始化
    7、不要依赖于线程调度器
    8、避免使用线程组

  有关代码:

package chapter9;

/**
 * @author zhen
 * @Date 2018/10/9 16:24
 */
public class Demo {

   /* 延迟初始化holder class模式
   private static class FieldHolder {
        static final FieldType field = computeFieldValue();
    }

    static FieldType getField(){
        return FieldHolder.field;
    }*/
}
Demo
package chapter9;

/**
 * @author zhen
 * @Date 2018/10/9 15:52
 */
public class StopThread {
//    private static boolean stopRequested;
//
//    private static synchronized void requestStop(){
//        stopRequested = true;
//    }
//
//    private static synchronized  boolean stopRequested() {
//        return stopRequested;
//    }
//
//    public static void main(String[] args) throws InterruptedException{
//        //这里运行了1s不会自己停止,应为stopRequested的读取与改变没有同步
//        Thread backgroundThread = new Thread(new Runnable() {
//            public void run() {
//                int i = 0;
////                while(!stopRequested){
//                while(!stopRequested()){
//                    i++;
//                }
//            }
//        });
//        backgroundThread.start();
//
//        Thread.sleep(1000);
////        stopRequested = true;
//        requestStop();
//    }

    private static volatile boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while(!stopRequested){
                    i++;
                }
            }
        });
        backgroundThread.start();

        Thread.sleep(1000);
        stopRequested = true;
    }
}
StopThread

 

posted @ 2018-10-09 17:10  guodaxia  阅读(57)  评论(0)    收藏  举报