I searched a lot, but could not find a specific solution. There are also some questions regarding this in stackoverflow, but I cannot find a satisfactory answer, so I ask it again.
I have a class as indicated in java. I know how to use streams in java.
//please do not consider syntax if there is printing mistake, as i am typing code just for showing the concept in my mind public class myclass{ private List<String> mylist=new ArrayList<String>(); public addString(String str){ //code to add string in list } public deleteString(String str){//or passing an index to delete //code to delete string in list } }
Now I want to do these two operations at the same time. for this, I created two threads, one of which executes addString () logic in run, and the other executes deleteString () logic.i passes mylist in the constructor of each thread, but how can I return an object after adding and deleting to mylist?
Before I thought that "if I pass mylist in the constructor of the stream, it passes the address mylist to the stream and the stream performs operations on it that the changes apply to the mylist object." But this is not the case as changes are not reflacted to the mylist object. can anyone articulate this?
What is the best way to achieve this?
the requirement is that if a thread inserts an element, the last other thread should be able to delete some element in another index, say the second at the same time.
EDIT
I did it like this: thanx to Enno Shioji
public class myClass { private List<String> mylist = Collections.synchronizedList(new ArrayList<String>()); public myClass(){ mylist.add("abc"); mylist.add("def"); mylist.add("ghi"); mylist.add("jkl"); } public void addString(String str) { mylist.add(str); } public void displayValues() { for (int i = 0; i < mylist.size(); i++) { System.out.println("value is " + mylist.get(i) + "at " + i); } } public void deleteString(int i) { mylist.remove(i); } } class addThread { public static void main(String a[]) { final myClass mine = new myClass(); Thread t1 = new Thread() { @Override public void run() { mine.displayValues(); mine.addString("aaa"); mine.displayValues(); } }; Thread t2 = new Thread() { public void run() { mine.displayValues(); mine.deleteString(1); mine.displayValues(); } }; t1.start(); t2.start(); } }
Is there any other way to do this?