Synchronized methods and thread locking

Hi can someone please explain the difference between these two examples in the context of object locking
public void method1(){
    synchronized(this){
}And
StringBuffer aStringBufferObject = new StringBuffer("A");
public void method2(){
    synchronized(aStringBufferObject){
}I know the first example will obtain a lock on the this instance and the second will obtain a lock of the aStringBufferObject instance. But i dont really understand what the effect or the difference of teh two is.
For example, in the second example, will threads still be able to execute the code inside the synchronized block because the lock is not related to the 'this' instance?
I know that synchronizing a method or a block of code prevents multiple threads to access that block/method at the same time but what is the purpose of specifying the object to lock on and what is the difference in the way the object is specified as in teh above examples.
Thanks
Edited by: ziggy on Jul 24, 2011 3:23 PM

Shortly put, the synchronized(object) doesn't lock the object reference in any way. It locks the code inside the synchronized's brackets, so that code can run it only when they have locked object (or in truth, when they have acquired object's monitor).
Since only one thread at a time can lock an object (obtain an object's monitor), this means that 2 threads executing blocks that synchronize on the same object can't run at the same time, ensuring thread safety (among other things).

Similar Messages

  • Differences between Synchronized methods and blocks

    Hi all,
    I would like to differences between Synchronized methods and blocks.
    - Muni

    Well, you'll get so many of right answers in next ten to thirty minutes.
    I like to yield :)
    Oooo... Ten minutes has passed.
    Synchronized block is a toilet room with a lock in a public lavatory.
    Only one person(running thread) can have the lock at a time.
    And, she/he have to receive the lock from a particular object obj like:
    synchronized(obj){.....} // one object has only one lock for this {} toilet and for any other toilets how many there are... *
    (*: In other words, while a thread is executing a synchronized(obj){} block, other threads can't enter other synchronized(obj){} blocks.)
    Synchronized method is a kind of synchronized block.
    This special block is defaulted to have lock from the object on which the method is defined.
    public class Foo{public synchronized Method(){}}
    use the lock of a Foo object.
    Message was edited by:
    hiwa
    Message was edited by:
    hiwa

  • Synchronized method in Thread

    Hi All,
    Can u show how to use synchronized method in thread.So that only one thread can access the resource at a time so that other needs to wait.Can u give me a sample example regarding this.So that it will be much more useful.
    Thanx,
    m.ananthu

    synchronized public void method1(){
    // code for the method....
    }Hope it helps.

  • How to stop an execution from a method and thread?

    1,
    public void method(){
    if( something is true)
    //I want to stop this method
    //or if something is false, go on
    blablablablabla
    }Does any one know how to solve the above??
    2,
    Thread t = new Thread(){
    public void run(){
    if( something is true)
    //I want to stop and kill this Thread
    //or if something is false, go on
    blablablablabla
    }Again, how do I solve the above??
    I know this is very simple, but I just hit a wall when I encounter this on making a program for my project.
    please help
    thanks alot

    warnerja, for the method, I have tried "return" but
    it does not work... will it work on the run method of
    thread object??
    Secondly, doesn't "break" keyword only stops the
    execution of a loop/condition, but not the method's
    scope??yes. break breaks the loop. I thought your method doesnt have any other code except the condition.
    use return with thread.

  • Static method and threads?

    I have a question regarding "static". for example, I have the following code
    class Test{
    public int i=0;
    public static calculateInt(){
    ....some operations on i;
    if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
    what if I change "public i" to :private i", the same effects?

    You can't operate on i in a static method, since i is an instance variable.
    If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
    If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Synchronizing methods and a static main method

    I have a class with a static main method, calling 3 different jdbc updates.
    I want to make sure this is thread safe when called for various clients.
    It's goes:
    args[0] = clientI
    update 1:update field1 where clientid = client1
    update 2:update field2 where clientid = client1
    update 3:update field3 where clientid = client1I assume I am in jeopardy of mixing up my data?
    I don't think I can synchronize a main method, nor would it do any good to synchronize the class?
    Should I break the updates into methods, then synchronize them, or synchronize parts of the code?
    you opinion would help greatly.

    You haven't provided enough information.
    Are those updates occurring sequentially? Then it's threadsafe.
    Are they running in different threads? Then to make them threadsafe you'll need proper synchronization, or a database transaction.
    Of course, looking at those particular updates, I don't see any reason why you'd need to worry about thread safety. They look to be independent of each other. Or perhaps you meant you need them to be atomic? That is, any query will see either the old values of all three fields, or the new values of all three fields. Nobody will be able to see the new values for fields 1 and 2, but the old value for field 3. If that's the case, then those three updates need to be in a database transaction.

  • Post Deleted and thread locked

    >Post deleted for violation of the VZW ToS. Discussing of rooting/hacking/jailbreaking etc., is not permitted on this site.<
    Verizon Wireless Terms of Service
    Message was edited by: Verizon Moderator

    That is a custom ROM and you will have to void your phone's warranty to install. That is all I'm going to say about it since any more discussion is a TOS violation.

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • Static synchronized methods VS non-static synchronized methods ??

    what is the difference between static synchronized methods and non-static synchronized methods as far as the behavior of the threads is concerned? if a thread is in static synchronized method can another thread access simple (ie. non static) synchronized methods?

    javanewbie80 wrote:
    Great. Thanks. This whole explanation made a lot of sense to me.Cool, glad I was able to help!
    Probably I was just trying to complicate things unnecessarily.It's a classic case of complexity inversion. It seems simpler to say something like "synchronization locks the class" or "...locks the method" than to give my explanation and then extrapolate the implications. Just like the seemingly simpler, but incorrect, "Java passes objects by reference," vs. the correct "Java passes references by value," or Java's seemingly complex I/O vs. other languages' int x = readInt(); or whatever.
    In the seemingly complex case, the primitive construct is simpler, but the higher level construct requires more assembly or derivation of the primitive constructs, making that case seem more complicated.
    Okay, I just re-read that, and it seems like I'm making no sense, but I'll leave it, just in case somebody can get some meaning out of it. :-)

  • Range of synchronized method?

    Hi,
    If you have a synchronized method, which calls another method, is that other method also synchronized?
    protected synchronized void doSomething() {
        // ... some coding
        heavyNumberCrunching()
        // ... some more coding
    protected void heavyNumberCrunching() {
        // ... even more coding
    }Additions:
    1. only doSomething() calls heavyNumberCrunching()
    2. heavyNumberCrunching() reads from/writes to collections, that can be accessed by other thread. Will access to these collections (not necessarily a Vector or Hashtable) be restricted when heavyNumberCrunching is crunching away?
    Just wondering.
    Abel

    spoon_ wrote:
    Abel wrote:
    If you have a synchronized method, which calls another method, is that other method also synchronized?yes, This is incorrect.
    the lock is held from when the method begins to when it endsWhile it is true that the lock is held until the synchronized method ends, that lock does not prevent access to unsynchronized methods by other threads.
    An example:
    =============
    public class Crunch {
        Crunch() {
            Thread[] aTeam = new Thread[10];
            for (int i = 0; i < 10; i++) {
                aTeam[i] = new Thread(new Runnable() {
                    public void run() {
                        doSomething();
                }, "A Team Thread " + i);
                aTeam.start();
    Thread[] bTeam = new Thread[10];
    for (int i = 0; i < 10; i++) {
    bTeam[i] = new Thread(new Runnable() {
    public void run() {
    heavyNumberCrunching();
    }, "B Team Thread " + i);
    bTeam[i].start();
    public synchronized void doSomething() {
    heavyNumberCrunching();
    public void heavyNumberCrunching() {
    System.out.println("Crunching on thread: " + Thread.currentThread().getName());
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    System.out.println("Done crunching on thread: " + Thread.currentThread().getName());
    public static void main(String[] args) {
    new Crunch();
    The A Team threads all access the heavyNumberCrunching() method via the synchronized doSomething() method. The B Team threads call heavyNumberCrunching() directly.
    Here's some output from a run on my quad core machine:
    Crunching on thread: A Team Thread 0
    Crunching on thread: B Team Thread 0
    Crunching on thread: B Team Thread 1
    Crunching on thread: B Team Thread 2
    Crunching on thread: B Team Thread 3
    Crunching on thread: B Team Thread 4
    Crunching on thread: B Team Thread 5
    Crunching on thread: B Team Thread 6
    Crunching on thread: B Team Thread 7
    Crunching on thread: B Team Thread 9
    Crunching on thread: B Team Thread 8
    Done crunching on thread: B Team Thread 5
    Done crunching on thread: B Team Thread 4
    Done crunching on thread: B Team Thread 9
    Done crunching on thread: B Team Thread 3
    Done crunching on thread: B Team Thread 7
    Done crunching on thread: B Team Thread 1
    Done crunching on thread: B Team Thread 2
    Done crunching on thread: A Team Thread 0
    Done crunching on thread: B Team Thread 8
    Done crunching on thread: B Team Thread 6
    Done crunching on thread: B Team Thread 0
    Crunching on thread: A Team Thread 9
    Done crunching on thread: A Team Thread 9
    Crunching on thread: A Team Thread 8
    Done crunching on thread: A Team Thread 8
    Crunching on thread: A Team Thread 7
    Done crunching on thread: A Team Thread 7
    Crunching on thread: A Team Thread 6
    Done crunching on thread: A Team Thread 6
    Crunching on thread: A Team Thread 5
    Done crunching on thread: A Team Thread 5
    Crunching on thread: A Team Thread 4
    Done crunching on thread: A Team Thread 4
    Crunching on thread: A Team Thread 3
    Done crunching on thread: A Team Thread 3
    Crunching on thread: A Team Thread 2
    Done crunching on thread: A Team Thread 2
    Crunching on thread: A Team Thread 1
    Done crunching on thread: A Team Thread 1Notice while Team A Thread 1 is crunching, most of the B Team threads start and finish crunching. Nothing prevents a call to an unsynchronized block of code, even if that code is called from a synchronized block.
    Jim S.

  • Question on synchronized method / block and Thread Cache

    Hi all,
    I came across a blog post at http://thejavacodemonkey.blogspot.com/2007/08/making-your-java-class-thread-safe.html which is talking about making Java classes thread safe. But, I was surprised to see that a thread can have my class' instance variable in its cache. Also, I have couple of questions on the things posted in the blog. I want to get the opinion from Java experts here.
    1. Given the example class
    class MyClass{
         private int x;
         public synchronized void setX(int X) { this.x = x; }
         public synchronized int getX() { return this.x; }
    Having the following instructions in two threads won't guarantee that it will print 1 and 2 as other thread can get the slot and call setX to modify the value - Am I right?
    obj is an MyClass Instance available to both the threads
    Thread 1:
    obj.setX(1);
    System.out.println(obj.getX());
    Thread 2:
    obj.setX(2);
    System.out.println(obj.getX());
    It will print 1 and 2 (in any order) only if I synchronize these calls on "obj" as follows - Is my understanding correct or ???
    Thread 1:
    synchronized(obj)
    obj.setX(1);
    System.out.println(obj.getX());
    Thread 2:
    synchronized(obj)
    obj.setX(2);
    System.out.println(obj.getX());
    2. If my understanding on point 1 (given above) is right, What the blog-post says is wrong as I cannot even expect my thread 1 to print 1 and thread 2 to print 2. Then, again a question arises as why a thread cache has a object's instance variable value in its cache and need to make my instance variable volatile. Can anyone explain me in detail? Won't the thread always refer the heap for Object's instance variable value?
    Thanks in advance,
    With regards,
    R Kaja Mohideen

    your basic understanding (as far as i can understand what you've written) seems to be correct. if you run your first 2 threads, you can get "11", "12", "21", or "22" (ignoring newlines). if you run your second 2 threads, you can get "12" or "21".
    i'm not sure i follow your second point about your thread's "cache". i think you are asking about the visibility of changes between threads, and, no, there is not concept of a shared "heap" in the memory model. basically, (conceptually) each thread has its own working memory, and it only shares updates to that memory when it has to (i.e. when a synchronization point is encountered, e.g. synchronized, volatile, etc). if every thread was forced to work out of a shared "heap", java on multi-core systems would be fairly useless.

  • What is a lock in a synchronized method ??

    Greetings,
    I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere where i update those variables ( So that variable doesn't update itself and lose its value as reset would be resetting that variable.) How do i lock all these variables in that reset method and how do i check for the lock where i would be updating that variable.
    Example: Psedo code
    class {
    int a =0;
    int b = 0;
    method update {
    a = 5;
    method update1{
    b = 6;
    synchronized method reset{
    a =0;
    b = 0;

    javanewbie83 wrote:
    Greetings,
    I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere where i update those variables ( So that variable doesn't update itself and lose its value as reset would be resetting that variable.) How do i lock all these variables in that reset method and how do i check for the lock where i would be updating that variable.You don't need to "check" for the lock. When you have a synchronized block or method, the synhcronized keyword tells the VM to stop executing that thread until it can attain the object's lock, then give the object's lock to that thread, and then take it back when the thread leaves the synchronized block (or calls wait()). It's all automatic.
    Note that you'll need to synchronize not only write access to the variable(s) in question, but read access also, in order to ensure that reader threads see the values written by writers.

  • Intrinsic locks - static synchronized method

    I am trying to understand the "static synchronized threads" - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. I wrote a sample program, but it is not giving me the desired results.
    I have 3 threads, t1, t2, t3. t1 calls a static synchronized method crazy(), where i am using static int i. t2 and t3 calls a void function f2() and f3() which just prints i. Now i put a sleep in synchronized method crazy. I am expecting t1 to start and print i and go to sleep for 10 secs, release i and then t2 and t3 starts since crazy() holds an intrinsic lock on i. But the program calls t2 and t3 even if crazy puts the thread to sleep. What happend to the intrinsic lock on i ??
    class RunnableThread implements Runnable{
    static String i;
    void f2() {
    RunnableThread.i = "Two";
    System.out.println(RunnableThread.i);
    void f3() {
    this.i = "three";
    System.out.println(this.i);
    static synchronized void crazy() {
    try {
    i = "One";
    System.out.println(i);
    Thread.sleep(10000);
    System.out.println("Sleep done");
    catch (Exception e ) {
    e.printStackTrace();
    public void run() {
    System.out.println("Thread Name: " + Thread.currentThread().getName());
    if (Thread.currentThread().getName().equals("two"))
    f2();
    } else if (Thread.currentThread().getName().equals("three"))
    f3();
    else if (Thread.currentThread().getName().equals("one"))
    RunnableThread.crazy();
    public static void main(String args[]) {
    System.out.println("SOP from main");
    RunnableThread rt1 = new RunnableThread();
    RunnableThread rt2 = new RunnableThread();
    RunnableThread rt3 = new RunnableThread();
    Thread t1 = new Thread(rt1, "one");
    t1.start();
    Thread t2 = new Thread(rt2, "two");
    t2.start();
    Thread t3 = new Thread(rt3, "three");
    t3.start();

    lavanya.km wrote:
    I am trying to understand the "static synchronized threads"Never heard of it. You might want to clarify your terminology.
    - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. Nope. Doesn't happen.
    I wrote a sample program,Ah, I see. You're creating synchronized static methods. Those do not even come close to "obtaining an intrinsic lock on all the static variables," even if there were such a thing as an "intrinsic lock," which there isn't. A synchronized method is just shorthand for enclosing the entire body in a sync block. In the case of a non-static method, it syncs on the "this" object. In the case of a static method, it syncs on the Class object for the class where the method is declared.
    In no case does anything sync on "all the variables," static or not.

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • [svn:bz-trunk] 12951: Changed synchronized PropertyProxyRegistry#getRegistry method to non-synchronized to avoid threads blocking in message push .

    Revision: 12951
    Revision: 12951
    Author:   [email protected]
    Date:     2009-12-15 02:17:31 -0800 (Tue, 15 Dec 2009)
    Log Message:
    Changed synchronized PropertyProxyRegistry#getRegistry method to non-synchronized to avoid threads blocking in message push.
    Checkintests: Pass with the usual 3-4 tests that time out with and without this change.
    QA: Yes
    Doc: No
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/PropertyProxyRegistry.java

    Revision: 12951
    Revision: 12951
    Author:   [email protected]
    Date:     2009-12-15 02:17:31 -0800 (Tue, 15 Dec 2009)
    Log Message:
    Changed synchronized PropertyProxyRegistry#getRegistry method to non-synchronized to avoid threads blocking in message push.
    Checkintests: Pass with the usual 3-4 tests that time out with and without this change.
    QA: Yes
    Doc: No
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/PropertyProxyRegistry.java

Maybe you are looking for