• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Basics of Thread and Synchronization

 
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
*/

 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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().
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 199
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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("]");
}
}
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
reply
    Bookmark Topic Watch Topic
  • New Topic