Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

java - 多线程时的异常行为(Unexpected behavior when multithreading)

I am having trouble debugging my code.

(我在调试代码时遇到问题。)

I am trying to implement multi-threading.

(我正在尝试实现多线程。)

Sometimes the output I receive is 77777, otherwise it is 97777. Why is this the case?

(有时我收到的输出为77777,否则为97777。为什么会这样?)

public class Concepts extends Thread {

    int code = 9;

    public void run() {
        this.code = 7;
    }

public static void main(String[] args) {

        Concepts co = new Concepts();
        co.start();
        for (int i = 0; i < 5; i++) {
            System.out.print(co.code + "==");
            System.out.println(Thread.currentThread().getName());
        }
    }
}
  ask by Yash Pandey translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are executing a second thread that sets the code instance variable to 7 without any synchronization.

(您正在执行第二个线程,该线程将code实例变量设置为7而没有任何同步。)

And you access the code variable from your main thread, again without any synchronization.

(而且,您可以再次从主线程访问code变量,而无需进行任何同步。)

This means that the main thread may see the state of the code variable prior to the other thread setting it to 7 (which means it would print 9 until it observes the change made by the other thread), or it may not (which means it would only print 7 s).

(这意味着主线程可能会在另一个线程将其设置为7之前先看到code变量的状态(这意味着它会打印9直到观察到另一个线程所做的更改),否则可能不会(这意味着它只会打印7秒)。)

It all depends on which thread will run first.

(这完全取决于哪个线程将首先运行。)

Without synchronization you have no reason to expect one outcome over the other.

(没有同步,您没有理由期望一个结果超过另一个。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...