简体   繁体   English

多线程不起作用。 什么不对?

[英]Multithreading doesn't work. What is incorrect?

It's a little program written with a purpose of studying multithreading. 这是一个旨在研究多线程的小程序。 I expected to get in main method different random numbers after run. 我希望运行后在main方法中获得不同的随机数。 About 4 numbers per second. 大约每秒4个数字。 But I got many thousands of zeros. 但是我有成千上万的零。 Where is an error? 哪里有错误?

Main Class: 主类:

public class Main {

public static void main(String[] args) {
        ExternalWorld externalWorld = new ExternalWorld();
        externalWorld.start();

        int x = 0;
        while (true) {
            while(!externalWorld.signal){
                System.out.println("qqq");}
            System.out.println(++x + ") " + externalWorld.getAnInt());
        }
    }
}

ExternalWorld Class: 外部世界类:

import java.util.Random;

public class ExternalWorld extends Thread {

    private int anInt = 0;
    public boolean signal = false;

    @Override
    public void run() {
        Random random = new Random(100);
        while(true) {
            anInt = random.nextInt(100);
            signal = true;
            try {
                Thread.sleep(200);
                signal = false;
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public int getAnInt() {
        if (!signal) {
            int p = 1 / 0;
        }
        int result = anInt;
        anInt = 0;
        return result;
    }
}

problem: 问题:

private int anInt = 0;
public boolean signal = false;

You are access those variables from one thread to another thus giving you 0 and false on the main thread 您正在从一个线程访问另一个线程的那些变量,从而在主线程上给您0false

solution: 解:

use volatile keyword to access those variables from multiple threads 使用volatile关键字从多个线程访问那些变量

sample: 样品:

private volatile int anInt = 0;
public volatile boolean signal = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 开关盒不起作用。 爪哇 - Switch case doesn't work. Java JSF 2.2表单上的tagmanager.js不起作用。 我究竟做错了什么? - tagmanager.js on JSF 2.2 form doesn't work. What am I doing wrong? javadoc中的-nodeprecated选项似乎不起作用。我能做什么? - The -nodeprecated option in javadoc doesn't seem to work. What can I do? 简单的 ArrayList.remove(int) 不起作用。 我做错了什么? - Simple ArrayList.remove(int) doesn't work. What I am doing wrong? Spring安全过滤器不起作用。 春虫? - Spring security filter doesn't work. Spring bug? 拆分字符串不起作用。 (未使用的局部变量的值) - Splitting String doesn't work. (value of local variable not used) Android Button ArrayList onClickListener不起作用。 为什么? - Android Button ArrayList onClickListener doesn't work. Why? 基本的EJB3项目无法正常工作。 NameNotFound异常 - Basic EJB3 project doesn't work. NameNotFound Exception Actionbarsherlock和searchview不起作用。 应用程序崩溃 - Actionbarsherlock and searchview doesn't work. Application crashes 存储库模拟不起作用。 返回错误的 Http 状态 - Repository mocking doesn`t work. Return wrong Http status
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM