Why does this threaded code not print anything? [closed]

can someone tell me what is wrong with here? It does not print out anything.

public class thread {
    public static void main(String[] args) {
    Thread mythread = new Thread();
    mythread.start();
    Thread mythread1 = new Thread();
    mythread1.start();

}
    public class mythread extends Thread{
        int i;
        public void run() {
            for(i = 0; i<10;i++)
                System.out.println(i);
        }

    }
}

Answer

You should know that:

  1. Classes always start with capital letter (for example MyThread) and every following words starts with capital too (so ‘my thread’ -> class MyThread)

  2. Name your classes, where you use main’ accordingly, for example my colleges use class Main or class ProjectRun etc.. Naming should always make sense.

  3. When you are implementing a method from your parent, always use @Override annotation (like you can see in my code below).

Here’s some code:

public class Main {

    public static void main(String[] args) {
        Thread myThread1 = new Main.MyThread();
        myThread1.run();
        Thread myThread2 = new Main.MyThread();
        myThread2.run();
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            for( int i = 0; i < 10; i ++ ) {
                System.out.println(i);
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *