3
Answers

Synchronizing Two Threads

Photo of aun_ee

aun_ee

20y
4.1k
1
I have two threads sharing an Arraylist. Thread 1 adds an object to the arraylist whereas thread 2 reads and remove the object from the array list. I want to synchronize them such that, whenever thread 1 has something to add to the list it should get full control of the arraylist and not have to wait for any lock ,whereas thread 2 can read and remove data from the list whenever thread 1 is not using it annd should unlock it as soon as thread 1 gets a data to write. Any ideas what will be a good technique to implement it? Thanks,

Answers (3)

0
Photo of aun_ee
NA 7 0 20y
Thanks for y0our help. But by using Arraylist.Synchronized can I force a particular thread to get access to the ArrayList right when it has data to write...even though there might be a thread already reading and removing data from the list.... What I want is to have my second thread to loose lock right away when thread 1 wants to add soething to add..and for the time thread one has nothing to write thread 2 should be able to read for the interval until thread 1 has something to write to it.
0
Photo of shimtanny
NA 440 0 20y
Hi Use the follwoning code: ArrayList al = new ArrayList(); // not synchronized ArrayList syncAl = ArrayList.Synchronized(al); // synchronized -> thread safe You can check with syncAl.IsSynchronized whether your instance of ArrayList is synchronized (= threadsafe) or not. Simon
0
Photo of abdullah
NA 111 0 20y
Hi...... In C# it is different than other languages like java.......java syncronize the two methods....where in C# you have to make the syncronization for the Object (Arraylist)... public static void add() { lock(arraylist) { // code to add to the arraylist goes here.... Thread.Sleep(100); } } the remove will be the same...... For any further information contact Me : abdullah02@gmail.com Good luck