ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 使用boolean var来停止线程

2019-08-26 18:12:43  阅读:236  来源: 互联网

标签:java multithreading java-me midp cldc


我有一本我正在学习的Java书,在其中一个例子中,我看到了一些可疑的东西.

public class ThreadExample extends MIDlet {
    boolean threadsRunning = true; // Flag stopping the threads

    ThreadTest thr1;
    ThreadTest thr2;

    private class ThreadTest extends Thread {
        int loops;

        public ThreadTest(int waitingTime) {
            loops = waitTime;
        }

        public void run() {
            for (int i = 1; i <= loops; i++) {
                if (threadsRunning != true) { // here threadsRunning is tested
                    return;
                }

                try {
                    Thread.sleep(1000);
                } catch(InterruptedException e) {
                    System.out.println(e);
                }
            }
        }
    }

    public ThreadExample() {
        thr1 = new ThreadTest(2);
        thr2 = new ThreadTest(6);
    }

    public void startApp() throws MIDletStateChangeException {
        thr1.start();
        thr2.start();

        try {
            Thread.sleep(4000); // we wait 4 secs before stopping the threads - 
                                // this way one of the threads is supposed to finish by itself
        } catch(InterruptedException e) {
            System.out.println(e);
        }

        destroyApp();
    }

    public void destroyApp() {    
        threadsRunning = false;

        try {
            thr1.join();
            thr2.join();
        } catch(InterruptedException e) {
            System.out.println(e);
        }

        notifyDestroyed();
    }
}

由于它是MIDlet应用程序,因此在启动时会执行startApp方法.为了简单起见,startApp方法本身调用destroyApp,因此程序会销毁,停止线程并通知销毁.

问题是,使用这个’threadsRunning’变量是否安全,并且在两个线程和destroyApp方法中使用它会在某些时候引起任何麻烦吗?声明前面的’volatile’关键字是否有助于同步它?

解决方法:

设置布尔值是原子的,并且在此示例中没有“读取然后修改”逻辑,因此在这种特定情况下不需要同步对变量的访问.

但是,变量至少应该标记为不稳定.

标记变量volatile不会同步线程对它的访问;它确保线程不会因为代码优化或值缓存而错过另一个线程对变量的更新.例如,没有volatile,run()中的代码可以在开始时只读取一次threadsRunning值,缓存值,然后每次在if语句中使用此缓存值,而不是再次从主内存读取变量.如果threadsRunning值被另一个线程更改,则可能无法获取它.

通常,如果您使用来自多个线程的变量,并且其访问权限未同步,则应将其标记为volatile.

标签:java,multithreading,java-me,midp,cldc
来源: https://codeday.me/bug/20190826/1732624.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有