Java中的同步行为不正确?

问题描述 投票:0回答:2
for (int i = 0; i < 3; i++) {
    list.add("test" + i);
}

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        synchronized (list) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            list.add("test3");
        }
    }
});

thread.start();

synchronized (list) {
    System.out.println(list);
}

我现在不理解的是,打印输出不包含“test3”。在线程停止println结束时不应该同步列表吗?

所以他们应该按顺序排列:

Thread.sleep();
list.add("test3");
println(list);

这是怎么回事?

java multithreading list concurrency synchronization
2个回答
0
投票

我现在不理解的是,打印输出不包含“test3”。在线程停止println结束时不应该同步列表吗?

这意味着你启动的线程将在主线程之前获得锁定。没有办法保证在Java中。事实上,它似乎反过来工作,主线程在第二个线程之前锁定,阻止第二个线程获取锁定。

您可以尝试使用wait / notify机制来确保主线程正在等待另一个线程终止:import java.util.ArrayList;

    for (int i = 0; i < 3; i++) {
        list.add("test" + i);
    }

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (list) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add("test3");
                // Notify the main thread
                list.notify();
            }
        }
    });

    thread.start();

    synchronized (list) {
        try {
            // wait for the other thread for a specified time to terminate
            // this will temporary release the lock for the second thread.
            list.wait(5000);
        } catch (InterruptedException e) {
            // see above..
            e.printStackTrace();
        }
        System.out.println(list);
    }

3
投票

在线程停止println结束时不应该同步列表吗?

只有在第二个线程的run()方法执行(特别是在其中执行synchronized (list)语句)在主线程的synchronized (list)语句执行之前启动时才会出现这种情况。

thread.start();之前调用synchronized (list) {System.out.println(list);}不保证第二个线程将在执行synchronized (list) {System.out.println(list);}之前开始运行。

© www.soinside.com 2019 - 2024. All rights reserved.