本文介绍了Java MultiThreading跳过循环并给出错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java MultiThreading跳过循环并给出错误结果

Java MultiThreading skips loop and gives wrong result

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,但未提供期望的结果.为什么线程缺少循环????

The final value of count should be 199998 but it is not giving the desired result.Why the threads are missing the loops ???

推荐答案

之所以发生,是因为线程T1和T2会同时(并发)更新 count

It happened because Thread T1 and T2 will update count at the same time (concurrency) like that:

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 MultiThreading跳过循环并给出错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:54