Question

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?

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top