Results 1 to 3 of 3
  1. #1
    jsmitha2009 is offline Member
    Join Date
    May 2012
    Posts
    2
    Rep Power
    0

    Question question about "synchronized"

    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 question I have is:

    the output will be different depends on LINE 31, and why?

    For example, if comment out line 31, the result will be
    Java Code:
    main b = 1000
    M1: b = 1000
    if leave line 31, the result will be
    Java Code:
    M2: b = 2000
    main b = 2000
    M1: b = 1000
    Can anyone help? Thanks at advance!

  2. #2
    jsmitha2009 is offline Member
    Join Date
    May 2012
    Posts
    2
    Rep Power
    0

    Default Re: question about "synchronized"

    Can anyone help, please?

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,423
    Rep Power
    25

    Default 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 & 40
    Last 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

  1. Replies: 1
    Last Post: 02-01-2012, 08:37 PM
  2. Replies: 1
    Last Post: 09-08-2010, 04:08 PM
  3. Replies: 5
    Last Post: 06-22-2010, 03:51 PM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •