• 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

synchronized is confused

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i had study the theme about Thread class some weeks with the book

Oreilly Java Threads 2nd Edition
Scott Oaks & Henry Wong

hence very good, i worked the chapther 3 about syncronization techniques,
all good, but exists a doubt that not able sleep.

Exactly in the keyword synchronized, the book says that exists syncronization
in methods and in a block of code that the programmer wants

i've writed and compiled the next excercise:

Exist a applet that generate 10 threads throught the interface Runnable, each thread
has your name and run. This class is MiClaseHiloAppletRunnable.

The task of each thread is print in console a message 100 times, the class that implements
the interface Runnable is called MiClaseHiloRunnable.

Let me show the code for each class:


public class MiClaseHiloRunnable implements Runnable
{


public synchronized void run()
{
Thread hilo = new Thread();
hilo = Thread.currentThread();

System.out.println("Iterando el hilo hijo llamado: " + hilo.getName());

for(int i=0; i < 100; i++)
{
System.out.println("Iteracion " + i + " del hilo: " + hilo.getName());
}
}
}




import java.applet.Applet;

public class MiClaseHiloAppletRunnable extends Applet
{
public void init()
{
for(int i=0; i < 10; i++)
{
MiClaseHiloRunnable mch = new MiClaseHiloRunnable();
Thread hilo = new Thread(mch,"Hilo " + i);
hilo.start();
}
}

}


i decided put the keyword synchronized in the method run() of the class MiClaseHiloRunnable
for that each thread individually prints the 100 messages and the rest of threads must wait
until the current thread prints the messages, ok?,....but this not is the behavior desired.

the messages are printed in any order and not printed the 100 messages at once.

i looked for in the book and found the next:


The point to remember here is that the lock is based on a specific object and not on any particular
method.

Assume that we have two AsyncReadSocket objects called a and b that have been created in
separate threads. One thread executes the a.getResult() method while the other thread executes the
b.getResult() method. These two methods can execute in parallel because the call to a.get-
Result() grabs the object lock associated with the instance variable a, and the call to b.getResult()
grabs the object lock associated with the instance variable b. Since the two objects are different
objects, two different locks are grabbed by the two threads: neither thread has to wait for the other.

ok, that is perfect and is understood, but how can i have 2 or more threads and that race for the
lock in the method synchronized?

i need that if a thread calls the method synchronized only that thread
can execute these statements and the other threads must wait until the current thread release the method
and continue the next thread?

Thanks for your time and help

Ron Thomas Tenrek
 
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
Hi,

Welcome to JavaRanch!

Try this:



I moved the declaration of "mch" outside the loop. Now all ten threads will be sharing the same Runnable object, and you'll find that only one of them can be in the run() method at a time.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jack Tenrek:

ok, that is perfect and is understood, but how can i have 2 or more threads and that race for the
lock in the method synchronized?



By not declaring the run method as synchronized. Rather, you want all the Runnables (or Threads--whichever you have here) to sync on the same lock. That means a sync block where you explicitly declare what you're syncing on.

Remember:
"this" will be different for each of your threads, so since each one obtains a different lock, none of them prevent any others from running.

So if you wanted only one thread's run() to execute at a time (which kind of defeats the purpose of having multiple threads, but we'll ignore that for this exercise) then you'd need this:
where "someLock" is any object that all the threads can see and can share as a lock. It might be the Class object for their class, or it might be an object you create specifically to serve as the lock--as long as all the threads sync on the same object.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic