File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Basics of Thread and Synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Basics of Thread and Synchronization" Watch "Basics of Thread and Synchronization" New topic
Author

Basics of Thread and Synchronization

Pratibha Malhotra
Ranch Hand

Joined: Dec 21, 2003
Posts: 199
Hi,
I seem to have forgot thread basics
In following program i have created 2 threads.
class extending Thread Class has two sunchronized methods ehere in one code in sec synchronized method ie callme2() calls callme1(). As per the output, it is possible..
Also,If a thread sleeps in a synchronized methos, other thread can enter into the same method. As per my knowledge so far it shuld not happen, but it is actually happening..
i think its time to open my books again


class threadtest
{static void print(String message)
{System.out.println(">>>>>> "+message);}
public static void main(String[] args)
{new SimpleThread("A").start();
new SimpleThread("B").start();
}
}
// **************************************************
class SimpleThread extends Thread
{public SimpleThread(String str)
{super(str); }
public void run()
{callme1();
callme2();
}
void callme1()
{threadtest.print("111");
synchronized(this)
{threadtest.print("in Callme1 "+getName());
try { sleep(5000);
} catch (InterruptedException e) {}
threadtest.print(getName()+" getting out of Callme1");
}
}
synchronized void callme2()
{threadtest.print("in Callme2 "+getName());
callme1();
threadtest.print(getName()+" getting out of Callme2");
}
}

/* Output
>>>>>> in Callme1 A
>>>>>> in Callme1 B
>>>>>> A getting out of Callme1
>>>>>> in Callme2 A
>>>>>> in Callme1 A
>>>>>> B getting out of Callme1
>>>>>> in Callme2 B
>>>>>> in Callme1 B
>>>>>> A getting out of Callme1
>>>>>> A getting out of Callme2
>>>>>> B getting out of Callme1
>>>>>> B getting out of Callme2
*/



~ Pratibha Malhotra<br /> <br />Sun Certified Java Programmer<br />SCEA 1.4 (In Progress)<br />~~~~~~~~~~~~~~~~~~~~~~~~~~~<br />"Many of life's failures are people who did not realize how close they were to success when they gave up!!"
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by Gunjan Malhotra:
Also,If a thread sleeps in a synchronized methos, other thread can enter into the same method. As per my knowledge so far it shuld not happen, but it is actually happening..

No. Thread.sleep() does not release any locks; it holds on to them. You're thinking, I believe of Thread.wait().


[Jess in Action][AskingGoodQuestions]
Jacob George
Ranch Hand

Joined: Jun 26, 2001
Posts: 46
Originally posted by Gunjan Malhotra:
Hi,
I seem to have forgot thread basics
In following program i have created 2 threads.
class extending Thread Class has two sunchronized methods ehere in one code in sec synchronized method ie callme2() calls callme1(). As per the output, it is possible..
Also,If a thread sleeps in a synchronized methos, other thread can enter into the same method. As per my knowledge so far it shuld not happen, but it is actually happening..
i think its time to open my books again


class threadtest
{static void print(String message)
{System.out.println(">>>>>> "+message);}
public static void main(String[] args)
{new SimpleThread("A").start();
new SimpleThread("B").start();
}
}
// **************************************************
class SimpleThread extends Thread
{public SimpleThread(String str)
{super(str); }
public void run()
{callme1();
callme2();
}
void callme1()
{threadtest.print("111");
synchronized(this)
{threadtest.print("in Callme1 "+getName());
try { sleep(5000);
} catch (InterruptedException e) {}
threadtest.print(getName()+" getting out of Callme1");
}
}
synchronized void callme2()
{threadtest.print("in Callme2 "+getName());
callme1();
threadtest.print(getName()+" getting out of Callme2");
}
}

/* Output
>>>>>> in Callme1 A
>>>>>> in Callme1 B
>>>>>> A getting out of Callme1
>>>>>> in Callme2 A
>>>>>> in Callme1 A
>>>>>> B getting out of Callme1
>>>>>> in Callme2 B
>>>>>> in Callme1 B
>>>>>> A getting out of Callme1
>>>>>> A getting out of Callme2
>>>>>> B getting out of Callme1
>>>>>> B getting out of Callme2
*/



Hi,
In the code you have given, 2 seprate Thread instances are being created; hence they are two different objects and object synchronization doesn't really matters. You should have created one runnable object and two threads to execute them. In the later case, the object will be locked and the threads will queue while executed. Btw. While calling Thread.sleep(), none of the acquired/locked resources will be released. Infact, this is one of the differences between calling sleep and wait.
regards
Pratibha Malhotra
Ranch Hand

Joined: Dec 21, 2003
Posts: 199

Hi,
Follwing is the code where in I have created two instances of caller which implements Runnable.
** if I call call(String s) from run follwing is the output which is not synchronized
[Hello[Pratibha][Hello]][Pratibha]
** if I call test.call(s)(test being another class) from run follwing is the output which is synchronized
[Hello][Pratibha]
The confusion about two thread in synchronization when a method in another class still persists. If I write same method in class impementing runnable, threads are not synchronized.

class testsynch
{static void print(String message)
{System.out.print(message);}
public static void main(String[] args)
{ caller ob1 = new caller("Hello");
caller ob2 = new caller("Gunjan");
try{ ob1.t.join();
ob2.t.join();
}catch(InterruptedException ie){}
}
}
//*********************************************
class caller implements Runnable
{ String s;
callme targ;
Thread t;
public caller(String msg)
{ s = msg;
t = new Thread(this);
t.start();
}
public void run()
{ call(s);
// test.call(s);
}
synchronized void call(String s)
{ testsynch.print("["+s);
try{ Thread.sleep(1000);
}catch(InterruptedException ie){}
testsynch.print("]");
}
}
class test
{
synchronized static void call(String s)
{ testsynch.print("["+s);
try{ Thread.sleep(1000);
}catch(InterruptedException ie){}
testsynch.print("]");
}
}
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Ernest Friedman-Hill:

No. Thread.sleep() does not release any locks; it holds on to them. You're thinking, I believe of Thread.wait().

Actually the comment was more inline with thread.sleep(). calling sleep() no other threads should be able to enter that method.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

It would help significantly if you took some time and cleaned up your posted code so we can read it.

Each object has its own lock. Synchronization will grab the lock on the object it is synching on.

This is an instance method. Calling it synchronizes on the object that it is called on.

This is a class method. Calling it synchronizes on MyClass.class object.
ill show a different way

thats the best I can explain.
Balbhadra Singh
Greenhorn

Joined: Oct 14, 2003
Posts: 13
Hi Gilbert,
Here is the formatted code.

class DataClass {

void callme1() {

synchronized(this) { // 1
ThreadTest2.print("in Callme1 "+Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}

ThreadTest2.print(Thread.currentThread().getName()+" getting out of Callme1");
}
}

synchronized void callme2() {
ThreadTest2.print("in Callme2 "+Thread.currentThread().getName());
callme1();
ThreadTest2.print(Thread.currentThread().getName()+" getting out of Callme2");
}

}

class ThreadTest2 {

static void print(String message) {
System.out.println(">>>>>> "+message);
}
public static void main(String[] args) {
new SimpleThread("A").start();
new SimpleThread("B").start();
}
}
// **************************************************
class SimpleThread extends Thread {

DataClass data = new DataClass();

public SimpleThread(String str) {
super(str);
}

public void run() {
System.out.println("in run "+Thread.currentThread().getName());
data.callme1();
data.callme2();
}


}


/* Output
in run A
>>>>>> in Callme1 A
in run B
>>>>>> in Callme1 B //2
>>>>>> A getting out of Callme1
>>>>>> in Callme2 A
>>>>>> in Callme1 A
>>>>>> B getting out of Callme1
>>>>>> in Callme2 B
>>>>>> in Callme1 B
>>>>>> A getting out of Callme1
>>>>>> A getting out of Callme2
>>>>>> B getting out of Callme1
>>>>>> B getting out of Callme2
*/

I expected that when thread A is already holding the lock for data object (at line 1) there shouldn't be line 2 in the output.

When thread A goes for sleep it doesn't leave lock but takes it along with it. Then why is line 2 in the out put?

Thanks in advance.
Balbhadra Singh
Greenhorn

Joined: Oct 14, 2003
Posts: 13
In my previuos code data object was not shared across threads. Now code works fine.

class DataClass {

void callme1() {

synchronized(this) { // 1
ThreadTest2.print("in Callme1 "+Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}

ThreadTest2.print(Thread.currentThread().getName()+" getting out of Callme1");
}
}

synchronized void callme2() {
ThreadTest2.print("in Callme2 "+Thread.currentThread().getName());
callme1();
ThreadTest2.print(Thread.currentThread().getName()+" getting out of Callme2");
}

}

class ThreadTest2 {


static void print(String message) {
System.out.println(">>>>>> "+message);
}
public static void main(String[] args) {
DataClass data = new DataClass();
new SimpleThread("A", data).start();
new SimpleThread("B", data).start();
}
}
// **************************************************
class SimpleThread extends Thread {

DataClass o = null;


public SimpleThread(String str, DataClass o) {
super(str);
this.o = o;
}

public void run() {
synchronized(o) {
System.out.println("in run "+Thread.currentThread().getName());
o.callme1();
o.callme2();
}
}


}


in run A
>>>>>> in Callme1 A
>>>>>> A getting out of Callme1
>>>>>> in Callme2 A
>>>>>> in Callme1 A
>>>>>> A getting out of Callme1
>>>>>> A getting out of Callme2
in run B
>>>>>> in Callme1 B
>>>>>> B getting out of Callme1
>>>>>> in Callme2 B
>>>>>> in Callme1 B
>>>>>> B getting out of Callme1
>>>>>> B getting out of Callme2
 
jQuery in Action, 2nd edition
 
subject: Basics of Thread and Synchronization
 
Similar Threads
Threads
Thread...
join()
Thread, Runnable interface, simple question
priortiy