-1

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.");
        }   
    }
}
ankush981
  • 5,159
  • 8
  • 51
  • 96

2 Answers2

1

You are not creating object of NuThread. That's why thread is not starting.

And it's not the best idea to start thread in the constructor, see here.

Community
  • 1
  • 1
Maksym
  • 4,434
  • 4
  • 27
  • 46
1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks! This is how threads are created in Herbert Schildt's book, although I do feel that you have a point. Something else (main?) should be creating and running threads. – ankush981 Nov 22 '14 at 17:19