Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help needed with understanding how this multi-threaded code works :)

Status
Not open for further replies.

JProg

Programmer
Apr 4, 2002
88
JP
Hi Everyone,

I am currently reading a book on multi-threading and up until recently I have been able to understand what is going on. The thing is the complexity of the code has just jumped up about two gears without warning. The code is now using inner classes which I am trying to develop an understanding of but I am not finding it easy going, and the book has been lite on explanations. If anybody can help with the following code it will be really appreciated.

public class SetPriority extends Object{ private static Runnable makeRunnable() { Runnable r = new Runnable() { public void run() { for(int i=0; i<5; i++) { Thread t = Thread.currentThread(); System.out.println("in run() - priority=" + t.getPriority() + ", name=" + t.getName()); try{ Thread.sleep(2000); }catch(InterruptedException x){ //ignore } } } }; return r; } public static void main(String[] args) { Thread threadA = new Thread(makeRunnable(), "threadA"); threadA.setPriority(8); threadA.start(); Thread threadB = new Thread(makeRunnable(), "threadB"); threadB.setPriority(2); threadB.start(); Runnable r = new Runnable() { public void run() { Thread threadC = new Thread(makeRunnable(), "threadC"); threadC.start(); } }; Thread threadD = new Thread(r, "threadD"); threadD.setPriority(7); threadD.start(); try{ Thread.sleep(3000); }catch(InterruptedException x){ //ignore } threadA.setPriority(3); System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority()); }}


My greatest challenge is understanding how the makeRunnable() method works. I don't understand how this inner class can be declared static and then multiple "instances" created from it. I know that I have no idea what is going on, please help!!!

Thanks for your time.

Regards

Davo

P.S.: If you know of any really good references on inner classes, particularly URL resources, please let me know. Thanks again.
 
Code:
public class SetPriority extends Object {
    private static Runnable makeRunnable() {
        Runnable r = new Runnable() {
            public void run() {
                for(int i=0; i<5; i++) {
                    Thread t = Thread.currentThread();
                    System.out.println("in run() - priority="
                        + t.getPriority() +
                        ", name=" + t.getName());
                    try {
                        Thread.sleep(2000);
                    }
                    catch (InterruptedException x) {
                        //ignore
                    }
                }
            }
        };
        return r;
    }
    public static void main(String[] args) {
        Thread threadA = new Thread(makeRunnable(), "threadA");
        threadA.setPriority(8);
        threadA.start();
        Thread threadB = new Thread(makeRunnable(), "threadB");
        threadB.setPriority(2);
        threadB.start();
        Runnable r = new Runnable() {
            public void run() {
                Thread threadC = new Thread(makeRunnable(), "threadC");
                threadC.start();
            }
        };
        Thread threadD = new Thread(r, "threadD");
        threadD.setPriority(7);
        threadD.start();
        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException x) {
            //ignore
        }
        threadA.setPriority(3);
        System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority());
    }
}
The static method returns an new implementation instance of the Runnable interface. Each Runnable instance is then used in a Thread instance constructor. To simplify:
Code:
public class SetPriority extends Object {
    private static Runnable makeRunnable() {
        Runnable r = new Runnable() { // create a Runnable implementaion instance
            // Must implement run() method of the Runnable interface
            public void run() {
                // do something
            }
        };
        return r;
    }
    public static void main(String[] args) {
        // create some Threads
        Thread threadA = new Thread(makeRunnable(), "threadA");
        Thread threadB = new Thread(makeRunnable(), "threadB");

        // set Thread priorities
        threadB.setPriority(2);
        threadA.setPriority(8);

        // start the Threads - calls the run() method of the Thread instance, which
        // will call the run() method the Runnable for Threads constructed this way
        threadA.start();
        threadB.start();
    }
}
Hope this helps. Cheers, Neil

 
Neil,

Thanks heaps with your help on this code. Do you think that you could spare a minute to further explain "implementation instance". I don't really understand this idea, it looks like an object is being instantiated from an interface, and obviously that is not possible. I have been reading up on inner classes, slowly developing an understanding of how they work.... but still a little blurry! Thanks again for your help :)

Regards

Davo
 
Runnable is an interface.
The static method makeRunnable() contains within it the creation of an anonymous class that implements the Runnable interface. The code is not very clear, and I would personally never write anything like that.

I would maybe do something like :


Code:
public class SetPriority {

   // an inner class
   class MyRunnable implements Runnable {
    public void run() {
	for(int i=0; i<5; i++) {
	    Thread t = Thread.currentThread();
	    System.out.println("in run() - priority="
		+ t.getPriority() +
		", name=" + t.getName());
	    try {
		Thread.sleep(2000);
	    }
	    catch (InterruptedException x) {
		//ignore
	    }
	}
    }
   }

   private static Runnable makeRunnable() {
        // The MyRunnable class implements Runnable interface
        // so can be instantiated.
	Runnable r = new MyRunnable() {
	return r;
   }
   
   public static void main(String[] args) {
      // bla bla bla
   }
}

--------------------------------------------------
Free Database Connection Pooling Software
 
In the words of others:

In my own words, specific to Java:

implementation - A concrete class that implements an interface. For example:
Code:
interface Animal {
    public void makeNoise();
}
class Dog implements Animal {
    private String name;
    public Dog(String name) {
        this.name = name;
    }
    public void makeNoise() {
        System.out.println(name+" barks");
    }
}

instance - A runtime object of a specific type. For example:
Code:
public class Test {
    public static void main(String[] arg) {
        Animal fido = new Dog("fido");
        Animal spud = new Dog("spud");
        Animal daisy = new Animal() {
            public void makeNoise() {
                System.out.println("moo");
            }
        };
        Animal[] instances = { fido, spud, daisy };
        for(int i = 0; i < instances.length; i++) {
            instances[i].makeNoise();
        }
    }
}

In the code above, the Dog class implements the Animal interface, as does the anonymous inner class. When the program is run, 3 instances are created: fido, spud, and daisy.

Try running the code ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top