Java Multiple Threads Demo not Working

I'm writing a small program to see how multiple threads can be run in Java. Not sure why I'm not getting any output:

class NuThread implements Runnable {
    NuThread() {
        Thread t = new Thread(this, "NuThread");
        t.start();
    }

    public void run() {
        try {
                for (int i=0; i<5; i++) {
                Thread th = Thread.currentThread();
                System.out.println(th.getName() + ": " + i);
                Thread.sleep(300);
            }
        } catch (InterruptedException e) {
            Thread th = Thread.currentThread();
            System.out.println(th.getName() + " interrupted.");
        }
    }
}

public class MultiThreadDemo {
    public static void main(String[] args) {
        NuThread t1, t2, t3;
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Main interrupted.");
        }   
    }
}
Jon Skeet
people
quotationmark

You're not creating any instances of NuThread. This line:

NuThread t1, t2, t3;

... just declares three variables. It doesn't create any instances. You'd need something like:

NuThread t1 = new NuThread();
NuThread t2 = new NuThread();
NuThread t3 = new NuThread();

Having said that, making a constructor start a new thread is a little odd in itself... it might be better to remove that and just have:

// TODO: Rename NuThread to something more suitable :)
NuThread runnable = new NuThread();
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
t1.start();
t2.start();
t3.start();

Note that it's okay to use the same Runnable for all three threads, as they don't actually use any state.

people

See more on this question at Stackoverflow