Static synchronized methods

Hi
Why dont we declare static methods synchronized especially if they are doing some complex calculation on some passed arguments ?
thanks
ali

lucky_ali80 wrote:
Hi guys
Thanks for your quick replies. But i am still a bit confused.Then you're making it more complicated than it is.
You synchronize a block of code when you want to makes sure only one thread at a time can obtain a given lock for that block of code. You declare an instance (non-static) method synchronized as a shorthand for synchronizing the block that is its body on this, and you declare a class (static) method synchronized as a shorthand for synchronizing its body on the Class object for that class.
>
For e.g my static function looks some thing like the one below:
public class MyClass
public static int computeSomething ( int a , int b)
// a number of lines of complex computation on a and b
return result.
Now Say its a webserver running with object1, object2, 3...10 of the same type being maintained by the server. (Not threads but objects)
say all these objects simultaneously call my static function with their respective arguments.
Would this cause any synchronization issues??No. As I said in my first reply, every thread has its own copy of local variables. This includes method parameters. Each thread has its own a and b here.
Now, if you're using some other data besides a and b, and if that data is shared among multiple threads, then you may have an issue. We can't say for sure because there are many different possible scenarios.
Edited by: jverd on Feb 10, 2009 11:58 AM

Similar Messages

  • Calling static synchronized method in the constructor

    Is it ok to do so ?
    (calling a static synchronized method from the constructor of the same class)
    Please advise vis-a-vis pros and cons.
    regards,
    s.giri

    I would take a different take here. Sure you can do it but there are some ramifications from a best practices perspective. f you think of a class as a proper object, then making a method static or not is simple. the static variables and methods belong to the class while the non-static variables and methods belong to the instance.
    a method should be bound to the class (made static) if the method operates on the class's static variables (modifies the class's state). an instance object should not directly modify the state of the class.
    a method should be bound to the instance (made non-static) if it operates on the instance's (non-static) variables.
    you should not modify the state of the class object (the static variables) within the instance (non-static) method - rather, relegate that to the class's methods.
    although it is permitted, i do not access the static methods through an instance object. i only access static methods through the class object for clarity.
    and since the instance variables are not part of the class object itself, the language cannot and does not allow access to non-static variables and methods through the class object's methods.

  • 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. :-)

  • Static synchronized method

    hi,
    I am unable to understand the concept of static synchronized method.
    A non-static synchronized method gets lock on this object before entering into the method. But how this is valid for static method.
    thanks in advance

    hi,
    I am unable to understand the concept of static
    atic synchronized method.
    A non-static synchronized method gets lock on
    this object before entering into the method.
    But how this is valid for static method.
    thanks in advanceIt locks the YourClassName.class object.

  • Multiple static synchronized methods locking the same object ?

    If I have multiple static synchronized methods in a class will all the methods lock on the same (Class) object ? I guess the answer to this would be yes. In that case is it possible achieve synchronization without an object ie code level synchronization ? If yes, how ?

    If I have multiple static synchronized methods in a
    class will all the methods lock on the same (Class)
    object ? I guess the answer to this would be yes. In
    that case is it possible achieve synchronization
    without an object ie code level synchronization ? If
    yes, how ?There is nothing special about static synchronized methods vs. any other synchronization. It's just shorthand for syncing on the Class object for that class. The effects of synchronization are identical no matter what you sync on.
    There's no way to achieve synchronization without an object. Synchronizing always obtains an object's lock. In the case of static synced methods, the object whose lock we obtain is the Class object for that class. As far as syncing goes, it's just another object.
    There is no such thing as "code level synchronization" vs. any other kind. All syncing occurs in your Java code over blocks of code. For synced methods, those blocks are the entire respective method bodies.
    Having said all that, I have no idea what you're really after or what you're trying to achieve.

  • 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.

  • 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();
    }

  • Doubt: About synchronized methods?

    Hi,
    Can any one let me know, Is there any difference between static and non-static synchronized methods? If yes, what is the difference?

    One is static and one isn't. What did you think?
    As I recall, non-static methods lock on the object, whereas static methods lock on the class object, if that's what you're wondering about.

  • Prblem calling synchronized method from onMessage

    Hi friends,
    I am trying to call a synchronized method "X" from onMessage method in MDB.
    I dont see any effect of synchronization....
    do i need to make the "X" method static synchronized??
    or else is there any other way ?
    I need ur help

    Hi,
    MDBs are not single threaded as messages are concurrently processed. You did not get any synchronisation as all your MDB instances (threads) are accessing a different instance of your object. But however, if you use a static synchronized method then all your MDB instances will be synchronized on the same object and that should have the expected behaviour.
    Arnaud

  • 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.

  • Synchronized method in a java class used by many interfaces

    My interface (idoc to file) is using a java class, which has one method that reads a table from a central database and after doing some calculations updates it.
    (The interface instantiate the class inside a user-defined function and calls the method there.)
    The problem is that if somebody sends 100 idocs at the same time, there can be a “dirty read”, I mean, a read just before other interface updates the table.
    We want the following:
    Interface 1:
    -          Read counter from the table (counter = 5 )
    -          Increment counter (counter = 6)
    -          Update table with that counter (table with counter = 6)
    Interface 2:
    -          Read counter from the table (counter = 6 )
    -          Increment counter (counter = 7)
    -          Update table with that counter (table with counter = 7)
    RESULT: The table has the counter = 7
    But what is happening is the following:
    -          Interface 1 reads (counter = 5)
    -          Interface 2 reads (counter = 5)
    -          Interface 1 increments counter (counter = 6)
    -          Interface 2 increments counter (counter = 6)
    -          Interface 1 updates table (table with counter = 6)
    -          Interface 2 updates table (table with counter = 6)
    RESULT: The table has the counter = 6 (WRONG)
    I made the method synchronized. What I was expecting was that only one interface (i1) could enter the method (read the table and update it) while other interfaces running at the same time would have to wait until i1 finished that method.
    My first test indicates that's not happening. Can anybody help me to find a solution?

    Hi Bhavesh,
    If the QOS is EOIO this means that the integration engine manage the call to the mapping program (and all the other blocks) inside an "internal" synchronized method.
    So this means that in this case you do not need to manage the queued access (synchronization) inside your custom java code because it is already enveloped in a queued block by XI.
    The problem that Jorge had can be easily reproduced using the sample code that follows:
    <b>class Synch Object</b>
    import java.util.Date;
    public class SynchObject {
         String strName;
         public SynchObject(String strName){
              this.strName = strName;
         public synchronized void syncWrite(String strCaller) throws InterruptedException{
              Date now;
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " entering syncWrite of " + strName);
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " syncWrite of " + strName + " called by " + strCaller );
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " leaving syncWrite of " + strName);
              System.out.println("");
              System.out.flush();
    <b>class Caller</b>
    public class Caller implements Runnable {
         String strName;
         SynchObject target;
         int intMax;
         public Caller(String strName, SynchObject target, int intMax) {
              this.strName = strName;
              this.target = target;
              this.intMax = intMax;
         public void run() {
              for(int i=0; i<intMax;i++)
                   try {
                        target.syncWrite(strName);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
    <b>class Workbench</b>
    public class Workbench {
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SynchObject sObj1 = new SynchObject("syncObj1");
              SynchObject sObj2 = new SynchObject("syncObj2");
              Caller c1 = new Caller("caller1",sObj1,2);
              Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
              Thread ct1 = new Thread(c1);
              Thread ct2 = new Thread(c2);
              ct1.start();
              ct2.start();
    Run the workbench class to see what happen when setting QOS EOIO (the synch object is the same).
    To see instead what happen now (missing synchronization) you have to change in Workbench class the statement
    Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
    with
    Caller c2 = new Caller("caller2",sObj2,2); '[*CHANGE*]
    The reason is that every instance of the mapping program declare a new instance of the "Synchronized object" so the calls are synchronized inside the same mapping program but not between several mapping program.
    Hope this give you a better idea on this problems with java synchronization, but if you have further doubts (I know it's a little bit tricky ) feel free to ask.
    Kind Regards,
    Sergio

  • Dont understand Synchronized method to complete program

    I'm trying to finish theis program but i don't understand synchronized methods. I checked the java tutorial and i am still confused. Can someone help me approach finishing this program. Here is the spec and the first part of the program i have done.
    ===================================================================================
    When the above is working, create a class called Food. The objective here is to demonstrate the behavior of threads that share data, and use synchronized methods.
    Simulating an animal eating, simply means that the thread will sleep for some length of time.
    There is one instance of the Food class that is shared by both of the animals. Pass it to the constructor of the Animal class.
    There is a method in the Food class called eat(). This method is synchronized, i.e., only one Animal can be eating at a time.
    The rabbit eats the food (the thread will sleep) for a longer time than the turtle, thus giving an advantage to the rabbit.
    But, the turtle must wait until the rabbit is done eating until it can eat, so the advantage is reduced. Print out a message in the eat method when the animal begins to eat, and when it is done eating. Indicate which animal it is that starts to eat.
    Try making the eat method not synchronized, and observe the different behavior if the eat method allows the rabbit to begin eating before the turtle is done eating
       import java.util.Random;
        public class Animal extends Thread implements Runnable{
          private String name;
          private int position;
          private int speed;
          private int restMax;
          public static boolean winner = false;
          Random random = new Random();
           public Animal (String name, int position, int speed,int restMax){
             this.name = name;
             this.position = position;
             this.speed = speed;
             this.restMax = restMax;
           public void run(){
             try{
                while( winner == false){
                   if(position < 100){
                      Thread.sleep(random.nextInt(restMax));
                      position += speed ;
                      System.out.println(name+" is in "+ position+" position ");
                   if (position >= 100){
                      winner = true;
                      System.out.println(name+" is the winner");
                      System.exit(0);
                 catch(InterruptedException e){
           public static void main(String[] args){
             Animal rabbit = new Animal("trix", 0, 5, 150);
             Animal turtle = new Animal("maury",0, 3, 100);
             rabbit.start();
             turtle.start();
       }

    Example:class Donkeyphile implements Runnable {       
        private Donkey donkey;
        private long time;
        Donkeyphile(Donkey donkey, long time) {
            this.donkey = donkey;
            this.time = time;
        public void run() {
            for (int i = 0; i < 10; i++) {
                donkey.love(time);
        public static void main(String[] args) {
            Donkey donkey = new Donkey();
            Donkeyphile jverd = new Donkeyphile(donkey, 500);
            Donkeyphile yawmark = new Donkeyphile(donkey, 100);
            Thread j = new Thread(jverd, "Jverd");
            Thread y = new Thread(yawmark, "Yawmark");
            j.start();
            y.start();
    class Donkey {
        synchronized void love(long time) {
            String name = Thread.currentThread().getName();
            System.out.println(name + " hugs the donkey.");
            try { Thread.sleep(time); } catch (InterruptedException e) { }
            System.out.println(name + " releases the donkey.");
    }

  • Synchronized methods trouble

    hey guys,
    I was under the impression that when u use synchronized methods, when a thread calls it any other threads calling it have to wait. If thats true then can someone help me and point out why my threads aren't waiting :(.
    import java.util.*;
    public class cannibal implements Runnable {
        private static int nonCannibal = 0;
        cannibal(){}
        public synchronized void eat(){
            boolean flag = false;
            try{
                while(nonCannibal == 0){
                    if(flag == false){
                        System.out.println("A cannibal waits in the darkness...");
                        flag = true;
                    wait();
            }catch(InterruptedException e){
                System.out.println("Some Exception!");
            nonCannibal--;
            System.out.println("Cannibal just ate someone in the woods!");
            System.out.println(nonCannibal +" survivors left!");
        public synchronized void dontEatMe(){
            nonCannibal++;
            notify();
            System.out.println("Unsuspecting person ventures to far out in the woods!");
        public synchronized void run(){
            Random generator = new Random();
            int x = generator.nextInt(2);
            if(x == 0){
                //System.out.println("Cannibal was just summoned!");
                eat();
            }else if(x == 1){
               // System.out.println("Unsuspecting Person just summoned!");
                dontEatMe();
         public static void main(String[] args) {
            Thread []x = new Thread[10];
            for(int i = 0; i < 10; i++){
                x[i] = new Thread(new cannibal());
                x.start();
    try{
    Thread.currentThread().sleep(3000);
    }catch(InterruptedException e){

    Demo:
    import java.util.Random;
    class Account {
        private int balance;
        public synchronized void deposit(int amount) {
            if (amount < 0) throw new IllegalArgumentException();
            System.out.println("increasing balance " + balance + " by " + amount);
            balance += amount;
            notifyAll();
        public synchronized void withdraw(int amount) throws InterruptedException {
            if (amount < 0) throw new IllegalArgumentException();
            while (balance < amount) {
                wait();
            System.out.println("decreasing balance " + balance + " by " + amount);
            balance -= amount;
    class Depositer implements Runnable {
        private Account account;
        public Depositer(Account account) {
            this.account = account;
        public void run() {
            try {
                Random rnd = new Random();
                for(int i=0; i<10; ++i) {
                    account.deposit(rnd.nextInt(100));
                    Thread.sleep(1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
    class Withdrawer implements Runnable {
        private Account account;
        public Withdrawer(Account account) {
            this.account = account;
        public void run() {
            try {
                Random rnd = new Random();
                for(int i=0; i<10; ++i) {
                    account.withdraw(rnd.nextInt(200));
            } catch(InterruptedException e) {
                e.printStackTrace();
    class MainClass {
        public static void main(String[] args) {
            Account acct = new Account();
            Withdrawer out = new Withdrawer(acct);
            Depositer in = new Depositer(acct);
            new Thread(out).start();
            new Thread(in).start();
    }

  • Synchronized method / synchronized blocks

    What is the difference between using the synchronized keyword to make a method synchronized and using synchronized blocks? The book that I have only offers a brief explanation of synchronized blocks that is semantically termed as, "a block that allows arbitrary code to be synchronized on the monitor of an arbitrary object."
    Thanks in advance for any help.

    Synchronizing an instance method is semantically equivanlent to synchronizing the entire body of that method on this.
    Synchronizing a static method is semantically equivanlent to synchronizing the entire body of that method on the Class object representing the class that the method is defined in.
    i.e., The following two classes are equivalent:
    public class MyClass {
      public synchronized void instanceMethod() {
        //code...
      public static synchronized void staticMethod() {
        //code...
    public class MyClass {
      public void instanceMethod() {
        synchronized (this) {
          //code...
      public static void staticMethod() {
        synchronized (MyClass.class) {
          //code...
    }

  • 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.

Maybe you are looking for

  • Amount in local currency for GRs

    Hello gurus, can anyone please explain to me this phenomenon: We have got a PO for 10 pieces of a material. The price is $7,40 per 10 pieces, so $7,40 total. Someone posted a goods receipt for 7 pieces. For whatever reason the amount in local currenc

  • HT3529 my imessage isnt working, any ideas?

    My imessage is not working, it wont activate.  Any ideas?

  • FieldPoint automation project

    I use LabVIEW 7.1 and NI FieldPoint devices (FP-1000) for educational purposes. I want to control a automation unit which has got 6 digital input(DI) and 5 digital output(DO). I used the sequence structure, but actually I am not sure the solution whe

  • Firefox 4.0b.11 plugin container.exe using 20.24% CPU .. Why

    Environment: Windows 7 64bit 4GB Ram / 750GB HDD Firefox up and running with 9 tabs open, and firefox is minimized as I am working on something else. Any idea's why so much CPU for container.exe if its just sitting there.

  • Programmatic skinning, charts and images.  Oh My!

    So here is a sample of the code I'm working with: for (var i:int = 0; i< numBlocks; i++) { var tmpImg:Image = new Image(); tmpImg.source = "test_disc_one.png"; tmpImg.y = startY - (8*i); tmpImg.blendMode = BlendMode.NORMAL; trace("["+i+"]: " + this.p