Results 1 to 3 of 3
Thread: question about "synchronized"
- 05-14-2012, 10:54 PM #1
Member
- Join Date
- May 2012
- Posts
- 2
- Rep Power
- 0
question about "synchronized"
The question I have is:Java Code:public class TestSynchronize implements Runnable { int b = 100; @Override public void run() { try { method1(); } catch (Exception e) { System.out.println("oops,,,, "); } } public synchronized void method1() { b = 1000; try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Method - 1 Interrupted."); } System.out.println("M1: b = " + b); } public synchronized void method2() { // b = 2000; try { Thread.sleep(1500); } catch (InterruptedException e) { System.out.println("Method - 2 interrupted."); } b = 2000; // System.out.println("M2: b = " + b); } public static void main(String[] args) { TestSynchronize ts = new TestSynchronize(); Thread t = new Thread(ts); t.start(); ts.method2(); System.out.println("main b = " + ts.b); } }
the output will be different depends on LINE 31, and why?
For example, if comment out line 31, the result will be
if leave line 31, the result will beJava Code:main b = 1000 M1: b = 1000
Can anyone help? Thanks at advance!Java Code:M2: b = 2000 main b = 2000 M1: b = 1000
- 05-15-2012, 06:45 PM #2
Member
- Join Date
- May 2012
- Posts
- 2
- Rep Power
- 0
Re: question about "synchronized"
Can anyone help, please?
- 05-15-2012, 08:19 PM #3
Re: question about "synchronized"
Line 31 is a println(). It does nothing as a comment.
My output (with time):
main b = 1000 1337106415891
M1: b = 1000 1337106420899
method1() can execute between the execution of lines 39 & 40Last edited by Norm; 05-15-2012 at 08:35 PM.
If you don't understand my response, don't ignore it, ask a question.
Similar Threads
-
loop "play again" in an 8 ball game , loops but wont let me answer my "out.print"
By IareSmart in forum New To JavaReplies: 1Last Post: 02-01-2012, 08:37 PM -
Difference b/w "synchronized","synchronize",and "synchronized()"
By Bala_Rugan in forum New To JavaReplies: 1Last Post: 09-08-2010, 04:08 PM -
Question about error "Exception in thread "main" java.lang.NoSuchMethodError: main
By ferdzz in forum New To JavaReplies: 5Last Post: 06-22-2010, 03:51 PM -
MoneyOut.println("It took you (whats wrong?>",year,"<WW?) years to repay the loan")
By soc86 in forum New To JavaReplies: 2Last Post: 01-24-2009, 06:56 PM -
the dollar sign "$", prints like any other normal char in java like "a" or "*" ?
By lse123 in forum New To JavaReplies: 1Last Post: 10-20-2008, 07:35 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks