Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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_Synchronization_Thread Safety - Fatal编程技术网

Java 线程中的共享变量->;需要同步它们吗?

Java 线程中的共享变量->;需要同步它们吗?,java,multithreading,synchronization,thread-safety,Java,Multithreading,Synchronization,Thread Safety,下面的代码从一个大列表中创建任务,该列表被拆分为子列表(列表l): 问题: 是否确实需要从共享的kwarryduration实例同步setvaluefromtime函数? 我认为是的,因为如果调度程序在这一行之后停止,结果可能会有所不同 int currentDay = getCurrentCalendarDay(cal); 另一个线程使用此int值进行进一步的逻辑。需要同步的原因有两个 如果持续时间是可变和共享的,或者如果cal在其他线程之间共享,那么调用getCurrentCalendar

下面的代码从一个大列表中创建任务,该列表被拆分为子列表(列表l):

问题:

是否确实需要从共享的
kwarryduration
实例同步
setvaluefromtime
函数? 我认为是的,因为如果调度程序在这一行之后停止,结果可能会有所不同

int currentDay = getCurrentCalendarDay(cal);

另一个线程使用此int值进行进一步的逻辑。

需要同步的原因有两个

  • 如果持续时间是可变和共享的,或者如果cal在其他线程之间共享,那么调用
    getCurrentCalendarDay(cal)
    可能会产生不同的结果,而不是在输入方法时预期的结果。如果持续时间是可变和共享的,则这也适用于持续时间

  • 如果共享了
    kwContentArray
    ,则还需要同步


  • 故事的寓意是同步对所有共享可变数据的访问。

    好的…“cal”是在每个线程的构造函数中创建的,如下所示:GregorianCalendar cal=new GregorianCalendar();仍然需要同步吗?如果cal一次可以被多个线程访问和修改,则是。不是字段cal,而是cal.set(日历年,10)。因为cal是可变的,所以你会通过settersHmm进入一场数据竞赛,好吧……我会创建一个新问题,因为你的答案没有回答我的所有细节问题。无论如何,我都会接受你的答案,并创建更容易理解的代码。
    public class MainReadingTask implements Runnable {
    
    private KwArrayDuration duration;
    private List<Item> wis;
    
        public MainReadingTask(List<Item> wis, KwArrayDuration duration) {
           this.wis = wis;
           this.duration = duration;
        }
    
        @Override
        public void run() {
        try {
          for (Item wi : wis) {
            duration.setValueFromItem(wi.getId(), null, cal);
          }
        } catch (IOException e) {
            e.printStackTrace();
        }   
        }
    
    }
    
    public synchronized void setValueFromItem(String id, DurationTime duration, Calendar cal) {
       if(duration != null) {
        try {
           this.setDurationValues(id, duration, cal);
        } catch (IOException e) {
           e.printStackTrace();
        }
       } else {
        int currentDay = getCurrentCalendarDay(cal);
        long time = 0;
        for (int i = currentDay; i < kwContentArray.size(); i++) {
           KwArrayWrapper currentDayKW = kwContentArray.get(i);
           currentDayKW.setValues(wi, String.valueOf(time));
           kwContentArray.set(i, currentDayKW);
        }
       }
    }
    
    int currentDay = getCurrentCalendarDay(cal);