473,387 Members | 1,628 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Synchronization in Threads

17
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Administrator
*/
public class sync
{
public static void main(String[] args)
{
Thread t= new Thread(new class1());
Thread t1= new Thread(new class1());

t.start();
t1.start();
}
}
class class1 implements Runnable
{
static int balance=10;
public synchronized void run()
{
synchronized(this)
{
try {
get();
Thread.sleep(5000);
set();
} catch (InterruptedException ex) {
Logger.getLogger(class1.class.getName()).log(Level .SEVERE, null, ex);
}
}
}
public synchronized void set()
{
++balance;
System.out.println("balance is set Thread name=" + Thread.currentThread().getName() + " is =" + balance);
}
public synchronized void get()
{
System.out.println("balance in get Thread name=" + Thread.currentThread().getName() + "is=" + balance);
}
}


output of program:
balance in get Thread name=Thread-0 , is=10
balance in get Thread name=Thread-1 , is=10
balance is set Thread name=Thread-1 , is =11
balance is set Thread name=Thread-0 , is =12


Expected output:
balance in get Thread name=Thread-0 ,is=10
balance in get Thread name=Thread-0 ,is=11
balance is set Thread name=Thread-1 , is =11
balance is set Thread name=Thread-1 , is =12







public synchronized void run()
{

try {
get();
Thread.sleep(5000);
set();
} catch (InterruptedException ex) {
Logger.getLogger(class1.class.getName()).log(Level .SEVERE, null, ex);
}

}


According to syncronization , Thread t should first execute and than Thread t1.

but in my case Thread t first call get() method than goes to sleep (then it should execute set() as it is LOCKED due to synchronization ) but Thread t1 is able to access the get() method , which should not happen .
why its happening


Thanks in advance
Jan 24 '08 #1
4 2430
JosAH
11,448 Expert 8TB
If you implement a synchronized method it will synchronize on the object itself.
You create two class1 objects so they both synchronize on themselves, effectively
ignoring the lock being set on the other object.

You should/could add a static Object lock in the class1 class and synchronize
on that one.

kind regards,

Jos
Jan 24 '08 #2
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Administrator
*/
public class sync
{
public static void main(String[] args)
{
Thread t= new Thread(new class1());
Thread t1= new Thread(new class1());

t.start();
t1.start();
}
}
class class1 implements Runnable
{
static int balance=10;
public synchronized void run()
{
synchronized(this)
{
try {
get();
Thread.sleep(5000);
set();
} catch (InterruptedException ex) {
Logger.getLogger(class1.class.getName()).log(Level .SEVERE, null, ex);
}
}
}
public synchronized void set()
{
++balance;
System.out.println("balance is set Thread name=" + Thread.currentThread().getName() + " is =" + balance);
}
public synchronized void get()
{
System.out.println("balance in get Thread name=" + Thread.currentThread().getName() + "is=" + balance);
}
}


output of program:
balance in get Thread name=Thread-0 , is=10
balance in get Thread name=Thread-1 , is=10
balance is set Thread name=Thread-1 , is =11
balance is set Thread name=Thread-0 , is =12


Expected output:
balance in get Thread name=Thread-0 ,is=10
balance in get Thread name=Thread-0 ,is=11
balance is set Thread name=Thread-1 , is =11
balance is set Thread name=Thread-1 , is =12







public synchronized void run()
{

try {
get();
Thread.sleep(5000);
set();
} catch (InterruptedException ex) {
Logger.getLogger(class1.class.getName()).log(Level .SEVERE, null, ex);
}

}


According to syncronization , Thread t should first execute and than Thread t1.

but in my case Thread t first call get() method than goes to sleep (then it should execute set() as it is LOCKED due to synchronization ) but Thread t1 is able to access the get() method , which should not happen .
why its happening


Thanks in advance

Pls, you will change the synchronisation methods to be private method,try this..
not sure..If u find it pls post it.

by
ela
Jan 25 '08 #3
r035198x
13,262 8TB
Pls, you will change the synchronisation methods to be private method,try this..
not sure..If u find it pls post it.

by
ela
No. Read Jos' post above. He's right on the money.
Jan 25 '08 #4
hostel
17
No. Read Jos' post above. He's right on the money.


i got the solution what i wanted .

in order to achieve synchronization , we need to use threads on same object

for example
ie sample Obj = new sample();
Thread t1 = new Thread(Obj);
Thread t2 = new Thread(Obj);


but i was trying to achieve synchronization on two different object using non static method, which is not possible ( for non static method , synchronization is possible for two different thread referencing samer object).
. In order to achieve synchronization on different object u need to declare method as STATIC .
Jan 25 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Efim | last post by:
Hi, I have got some problem with sending of events in .NET. I am using remouting. The client has got 2 objects for receiving different types of events (responses and events) The server has got...
7
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates...
0
by: Ivan | last post by:
Hi there My work on threads continues with more or less success. Here is what I'm trying to do: Class JobAgent is incharged for some tasks and when it's called it starts thread which performs...
5
by: Cyrus | last post by:
I have a question regarding synchronization across multiple threads for a Hashtable. Currently I have a Threadpool that is creating worker threads based on requests to read/write to a hashtable....
4
by: scott | last post by:
hi all, Thx to any one that can offer me help, it will be much appreciated. iv got a multithreaded program and need to use thread synchronization. The synchronization does not have to...
5
by: fei.liu | last post by:
Hello, in the application I am developing, I am having trouble to synchronize event triggered actions using 'lock(ob){...};' technique. Here is a outline of my code: class C{ int x = 0; public...
12
by: emma_middlebrook | last post by:
Hi Say you had N threads doing some jobs (not from a shared queue or anything like that, they each know how to do their own set of jobs in a self-contained way). How can you coordinate them so...
5
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the...
6
by: Chris Ashurst | last post by:
Hi, I'm coming in from a despised Java background, and I'm having some trouble wrapping my head around sharing an object between multiple instances of a single class (in simpler terms, I would say...
1
by: putrycydestengier | last post by:
Hello everyone. I've got question you may consider simple. Im rather new to C#, and I am not quiet sure about one thing. I've found somewhere, that one of ways of synchronizing access of few...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.