Java Observable List项目在被线程更新时被删除

时间:2018-07-20 09:49:31

标签: java multithreading observablelist

我正在编写一个代码,其中可观察的列表A通过单独的线程进行更新,并且当此列表中的新项目得到更新时,侦听器会将同一项目发送到另一个列表(称为列表B)以进行进一步计算。此列表B假设需要5个项目并进行计算,然后从列表A中删除旧项目并获取新项目。目前,我在从列表B中删除项目时的代码也从列表A中删除了我不想要的项目,列表B仍然有前一个项目。任何帮助将不胜感激。

enter image description here

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

public class Window_Demo1 implements Runnable {

/**
 * @param args
 */

	public static ObservableList<Integer> lstA = FXCollections.observableList(new ArrayList<Integer>());
	public static List<Integer> win = new ArrayList<>();
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		   Window_Demo1 demo = new Window_Demo1();
		   Thread thread = new Thread(demo);
		   thread.start();
		   addtolstB(lstA,win);

	}
	
	public static void addtolstB(ObservableList<? extends Integer> items, List<Integer> lstB) {
		items.addListener((ListChangeListener<Integer>) c-> {
	        while (c.next()) {
	            if (c.wasAdded()) {
	            	lstB.addAll(c.getAddedSubList());
	            	System.out.println(lstB.toString()+ "Lst B Added: "+ Instant.now().getEpochSecond());
	            	
	            	if(lstB.size()==5) {
	            		items.removeAll(lstB);
	            	}
	            }
	            if (c.wasRemoved()) {
	            	lstB.removeAll(c.getRemoved());
	            	System.out.println(lstB.toString());
	            }
	        }
		});

	    for (Integer item : items) {
	    	lstB.add(item);
	    }
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {

		// TODO Auto-generated method stub
		for (int i = 0; i <= 100; i++) {

			lstA.add(i);
			System.out.println(lstA.toString()+ "Publisher Added: "+i+" at time: "+Instant.now().getEpochSecond());

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	
		
	}

}

此代码中的问题是: enter image description here

0 个答案:

没有答案