Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的多线程,生成了两个线程_Java_Multithreading - Fatal编程技术网

Java中的多线程,生成了两个线程

Java中的多线程,生成了两个线程,java,multithreading,Java,Multithreading,我用Java编写了一个多线程程序,如下所示:- public class Client { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Counter counter = new Counter(); int val = counter.getValue()

我用Java编写了一个多线程程序,如下所示:-

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        Counter counter = new Counter();

        int val = counter.getValue();
        while(val < 5){
            val = counter.getValue();
            System.out.println("In main thread : "+val);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

}
}

class Counter implements Runnable {

    private int countValue;
    Counter(){
        countValue = 0;
        Thread thread = new Thread(this ,"Counter A");
        Thread thread1 = new Thread(this    ,"Counter B");
        thread.start();
        thread1.start();
    }

    int getValue(){
        return countValue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while( countValue < 5){

                System.out.println("In child thread : "+ ++countValue );
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }

}
}
有人能详细解释一下这个输出是如何产生的吗?提前谢谢你,你有3个线程(主线程和2个子线程)都是并行运行的(除非你有一个单独的进程框),它们都在读写一个不受任何同步保护的资源
countValue


当你做这样的事情时,你会得到明显的随机输出。

具体来说,你需要帮助理解其中的哪一部分?这和你期望的有什么不同?这是家庭作业吗?或者您只是在探索线程?可能的重复(OP的代码略有不同,输出的原因是相同的)类似于在输出中打印“在主线程中:0”后在子线程中“直接打印”的方式:2。首先应该是“在子线程中:1”。为什么您认为它应该这样工作?您有两个线程正在更新争用中的值,没有同步。如果您只有一个子线程,它可能会像您期望的那样工作。增加子线程的数量会给您带来更奇怪的行为。这就是为什么像synchronized和Intelligent Framework这样的东西存在于并行处理中的原因。那么我如何通过哪种同步方法来保护countValue呢?最简单的方法可能是查看
AtomicInteger
,否则,您可能需要阅读线程是如何工作的,使用
synchronized
,我还建议不要将更新值作为println语句的副作用。volatile有一些wierd用法和副作用,因此存在AtomicX类型。例如:
…因为访问易失性变量从不持有锁,所以它不适用于我们希望将读更新写(如x++)作为原子操作的情况…
In main thread : 0  
In child thread : 2   
In child thread : 1   
In child thread : 3  
In child thread : 3  
In child thread : 4  
In child thread : 5  
In main thread : 5