-3

I am trying to learn multi-threading

public class WithSynchronizeMethodObject extends Thread
{
    SharedObject obj;
    WithSynchronizeMethodObject()
    {

    }

    WithSynchronizeMethodObject(SharedObject o)
    {
        obj=o;
    }

    @Override
    public void run()
    {
        for(int i=0;i<5;i++)
        {
            try
            {
                //calling object of method to add and print value, real life scenario performing any other operation
                obj.addAndPrint();                  int sleepTime=getRandom();
                System.out.println(" "+getName()+" sleep time is "+sleepTime);

                    //randomly making thread sleep,
                    Thread.sleep(sleepTime);


            }
            catch(InterruptedException ie)
            {

            }
        }
    }

    int getRandom()
    {
        int range = Math.abs(900) + 100;
        double random=Math.random() * range;
        return (int)((random<100)?(100+random):random) ;
    }
    public static void main(String args[])
    {
        SharedObject obj=new SharedObject();

        //passing same object in both threads
        WithSynchronizeMethodObject withOutObj1=new WithSynchronizeMethodObject(obj);
        WithSynchronizeMethodObject withOutObj2=new WithSynchronizeMethodObject(obj);

        //starting both thread almost together, 
        withOutObj1.start();
        withOutObj2.start();
    }
}
//custom shared object
class SharedObject
{
    int i;
    SharedObject()
    {
        i=0;
    }

    synchronized void addAndPrint()
    {
        ++i;
        System.out.print("i="+i);
    }
}

OUTPUT:

i=1 Thread-0 sleep time is 236
i=2 Thread-1 sleep time is 455
i=3 Thread-0 sleep time is 401
i=4 Thread-1 sleep time is 133
i=5 Thread-1 sleep time is 983
i=6 Thread-0 sleep time is 160
i=7 Thread-0 sleep time is 456
i=8 Thread-0 sleep time is 182
i=9 Thread-1 sleep time is 146
i=10 Thread-1 sleep time is 661

EDIT:

Made Object Synchronize

synchronized(obj)
            {
                try
                {
                    obj.addAndPrint();
                    int sleepTime=getRandom();
                    System.out.println(" "+getName()+" sleep time is "+sleepTime);

                    //randomly making thread sleep,
                    Thread.sleep(sleepTime);

                }
                catch(InterruptedException ie)
                {

                }
            }

Showing two inconsistent output OUTPUT:

1.

i=1 Thread-0 sleep time is 299
i=2 Thread-0 sleep time is 154
i=3 Thread-0 sleep time is 736
i=4 Thread-0 sleep time is 635
i=5 Thread-0 sleep time is 180
i=6 Thread-1 sleep time is 489
i=7 Thread-1 sleep time is 201
i=8 Thread-1 sleep time is 115
i=9 Thread-1 sleep time is 397
i=10 Thread-1 sleep time is 877

2.

i=1 Thread-0 sleep time is 618
i=2 Thread-0 sleep time is 125
i=3 Thread-0 sleep time is 170
i=4 Thread-0 sleep time is 705
i=5 Thread-1 sleep time is 431
i=6 Thread-1 sleep time is 738
i=7 Thread-0 sleep time is 821
i=8 Thread-1 sleep time is 296
i=9 Thread-1 sleep time is 536
i=10 Thread-1 sleep time is 143

Q.1 Why is the output not synchronized, how to make it run synchronized?

Q.2 What are other methods, i know few Locks and wait/notify?

Q.3 Which one and how exactly they help in synchronization?

Akhil Jain
  • 13,872
  • 15
  • 57
  • 93
  • 3 downvote and a close vote??? is that bad, i have asked specific question and to the point, why do this? – Akhil Jain Apr 30 '14 at 08:59
  • I didn't downvote, but it's not clear what you are trying to achieve or why. The whole point of using multiple threads is to make them as independent as possible. If you just wanted to run one, then the other, you would use a pair of loops and not use additional threads. – Peter Lawrey Apr 30 '14 at 09:47
  • i am new to concurrent programming , trying to see the possibility how will thread react when same object is shared, will synchronization help or not, how will it go, so just wrote code for experimenting, that is it!!! – Akhil Jain Apr 30 '14 at 09:58
  • The first example ran as I would have expected, and as I would have wanted, so it's not clear to me what the problem was. – Peter Lawrey Apr 30 '14 at 09:59
  • the output is not synchronized, that's where the problem is. I get a sense i have to read Java Concurrency in Practice. – Akhil Jain Apr 30 '14 at 10:03

1 Answers1

1

Why is the output not synchronized, how to make it run synchronized?

The output is synchronized. Each line is complete and correct. If it were not synchronized, you would see some lines inside another line.

I assume you mean;

how can I hold a lock for the whole loop?

Outside the loop you add

synchronized(sharedObject) {

and

}

at the end.

What are other methods, i know few Locks and wait/notify?

I highly recommended you read the book Java Concurrency in Practice. It is an excellent book, possibly the best written for Java.

Which one and how exactly they help in synchronization?

They have a number features which are interrelated

  • the obtain exclusive access to a resource using a combination of compare-and-set, possibly some state such as a queue of waiting threads, a call to the OS if there is a long delay.
  • a read/write memory barrier so that you get a consistent view of anything read/written in a similar block of code.
  • unlocking usually has checks that this is being called correctly.
  • some lock also can be monitored so you can see deadlocks, and waiting locks.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • @AkhilJain You are still only synchronizing for one iteration. If you want to synchronize for the whole run, you need to `synchronized` outside the loop. I am only guessing this is what you want to do, can you clarify what your expected output is? – Peter Lawrey Apr 30 '14 at 09:44
  • Lawery i just want that if `Thread-0` is accessing the `synchronized` object, will `Thread-1` wait for `Thread-0` to finish its execution ,before proceeding further, i want output that output one thread accessing one object at a time, and trying to achieve it – Akhil Jain Apr 30 '14 at 10:01
  • @AkhilJain This is what you had in the first example. If there was a problem you would see the same number `i=` twice or more. However the sleep in between makes it very unlikely the two threads will be accessing `i` at the same time anyway. – Peter Lawrey Apr 30 '14 at 10:20