java - Why do I need to synchronize this variable -
i have 4 threads each trying find max value in linked list.
this thread class:
public class mythread extends thread { linkedlist<integer> list; int max = integer.min_value; public mythread(linkedlist<integer> list) { this.list = list; } public void run() { synchronized (list) { /* if don't synchronize list, nosuchelementexception @ list.remove() */ while (!list.isempty()) { int num = list.remove(); if (num > max) { max = num; } } } } }
and here class main method:
public class application { public static void main(string args[]) throws interruptedexception { linkedlist<integer> list = new linkedlist<integer>(); (int = 0; < 10; i++) { list.add(i); } mythread t1 = new mythread(list); mythread t2 = new mythread(list); mythread t3 = new mythread(list); mythread t4 = new mythread(list); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); system.out.println(t1.max); system.out.println(t2.max); system.out.println(t3.max); system.out.println(t4.max); } }
in above code, have synchronize list
variable within run method or else i'll nosuchelementexception
@ list.remove()
. why case?
doesn't each thread have it's own list there no thread interference?
thanks
i address different part of question @rishi addressed:
doesn't each thread have it's own list there no thread interference?
the simple answer is: no, not. in java, when pass object of class type constructor or method, aren't passing obejct rather pointer it. if want pass separate copy of linked list each thread, need use linkedlist#clone.
if use clone, when thread removes 1 integer linked list, not removed other linked lists. paralellize this, should use standard array of numbers , assign segment of array each thread (ie. thread 1 0-9, thread 2 10-19, thread 3 20-29, etc.). array's contents visible threads created after contents deposited in array.
should note should not extend thread. instead, extend runnable , pass thread. furthermore, array(list) better 4 separate variables allows change number of threads later.
Comments
Post a Comment