『阿男的技术漫谈时间』*11*阿男和年糕重返volatile关键字与锁(上)_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 『阿男的技术漫谈时间』*11*阿男和年糕重返volatile关键字与锁(上)

『阿男的技术漫谈时间』*11*阿男和年糕重返volatile关键字与锁(上)

 2016/6/22 5:33:51  阿男bluedash  程序员俱乐部  我要评论(0)
  • 摘要:本集和年糕一起讨论并发编程的一些小故事。视频:『阿男的技术漫谈时间』*11*阿男和年糕重返volatile关键字与锁(上)本节课代码:/***Createdbywelion6/20/16.*/publicclassNoVolatile{booleanwaiting=true;publicvoidtest(){newThread(newRunnable(){publicvoidrun(){while(waiting==true){//wait}System.out.println
  • 标签:技术 关键字
本集和年糕一起讨论并发编程的一些小故事。

视频:『阿男的技术漫谈时间』*11*阿男和年糕重返volatile关键字与锁(上)

本节课代码:

class="java" name="code">
/**
 * Created by weli on 6/20/16.
 */
public class NoVolatile {
    boolean waiting = true;

    public void test() {
        new Thread(new Runnable() {
            public void run() {
                while (waiting == true) {
                    // wait
                }

                System.out.println("Thread 1 finished.");
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                // Sleep for a bit so that thread 1 has a chance to start
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignored) {
                }
                System.out.println("Thread 2 shutdown...");
                waiting = false;
            }
        }).start();
    }

    public static void main(String[] args) {
        new NoVolatile().test();
    }

}


/**
 * Created by weli on 6/20/16.
 */
public class UseVolatile {
    volatile boolean waiting = true;

    public void test() {
        new Thread(new Runnable() {
            public void run() {
                while (waiting) ;
                System.out.println("Thread 1 finished.");
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                // Sleep for a bit so that thread 1 has a chance to start
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignored) {
                }
                System.out.println("Thread 2 shutdown...");
                waiting = false;
            }
        }).start();
    }

    public static void main(String[] args) {
        new UseVolatile().test();
    }
}
发表评论
用户名: 匿名