Java 多线程跳过循环并给出错误的结果

标签 java multithreading

<分区>

Java 多线程跳过循环并给出错误结果

package Threading;

class DemoThread extends Thread{   //Thread Class   
    static int count=0;   // variable incremented by both the threads

    public DemoThread(String name) {
        // TODO Auto-generated constructor stub
        super(name);
    }

    public void run() { 
        for(int i=0;i<100000;i++) {
            count++;
            System.out.println(Thread.currentThread()+"Count"+count);  // print thread operating on count variable
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }       
    }   
}


public class MyThreadClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub      
        DemoThread t1=new DemoThread("T1");
        DemoThread t2=new DemoThread("T2");
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();  //allowing both the threads to complee before main thread
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Main Thread ends"+DemoThread.count);  //final value of count        
    }
}

count 的最终值应为 199998,但未给出所需的结果。 为什么线程缺少循环???

最佳答案

发生这种情况是因为线程 T1 和 T2 会像这样同时(并发)更新 count:

Thread[T1,5,main]Count10
Thread[T2,5,main]Count10
Thread[T1,5,main]Count12
Thread[T2,5,main]Count12
Thread[T2,5,main]Count14
Thread[T1,5,main]Count14
Thread[T1,5,main]Count15
Thread[T2,5,main]Count16

你应该使用 AtomicInteger

并更新您的代码:

static int count=0;static AtomicInteger count= new AtomicInteger();

count++;count.incrementAndGet();

关于Java 多线程跳过循环并给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585152/

相关文章:

java - Android 日志猫错误 ContextResult::kFatalFailure

java - ReentrantLock 显示 "unlocked"但第一个线程停止

java - 多次调用 java.util.zip.Deflater.setInput 在第一次之后什么都不做

c++ - Qt:复制隐式共享类的实例是线程安全的吗?

c# - 在控制台应用程序中同步来自不同线程的事件

java - 从 ManagedResource bean 公开 Collection<Something>?

java - Kotlin 中的注释不起作用

multithreading - Qt文档出了点问题

Ruby TCP/IP 客户端线程

java - 可以根据条件重新启动的线程