Saturday, 15 February 2014

java - syncronized block doens't block different objects -



java - syncronized block doens't block different objects -

i inserted in hashmap (for each row) this:

rows.put(currentrow, new object()); ....

and after threads phone call function:

@override public void run() { while (true) { increaserow(new random().nextint(10)); seek { sleep(3000); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } } public void increaserow(integer row) { synchronized (rows.get(row)) { (int j = 0; j < column; j++) { matrix[row][j] += 1; } system.out.println("begin print"); (int = 0; < this.row; i++) { system.out.println(); (int j = 0; j < column; j++) system.out.print(matrix[i][j]); } system.out.println(); system.out.println("end print"); } }

if start 1 thread, works ok, there problems more threads, like:

begin print 00000 begin print 00 0000000000000000 00 000000000000000000000 00000000000 00000000000000 00000000000 00 000000000000 111111111111 000000000000 111000000000000 000000000000 111111111111 000000000000 111111111111 000000000000 0000000100000 end print

the map 10 key-value , i' m syncronizing on object value, don't understand what's wrong.

thanks in advance.

to forcefulness print 'begin print' 'end print' each row update (not interleaved) need synchronize on 'rows' object.

while 1 thread @ time can write rows.get(0) object , can still lock on rows.get(0) , rows.get(1) , rows.get(2) objects concurrently. means output can contain 'begin print' multiple times in row followed multiple 'end print' lines.

depending on you're attempting accomplish here - output row you're updating since know 2 can done @ 1 time - synch row wish.

public void increaserow(integer row) { synchronized (rows.get(row)) { (int j = 0; j < column; j++) { matrix[row][j] += 1; } system.out.println(string.format("begin update row %s", row)); (int = 0; < this.row; i++) { system.out.println(); (int j = 0; j < column; j++) system.out.print(string.format("row %s value %s",row,matrix[i][j])); } system.out.println(); system.out.println("string.format("end update row %s", row)"); }

}

or if want each thread tell row updated:

public void increaserow(integer row) { synchronized (rows.get(row)) { (int j = 0; j < column; j++) { matrix[row][j] += 1; system.out.print(string.format("row %s value %s",row,matrix[row][j])); } } }

java multithreading

No comments:

Post a Comment