1

I'm new to threads in java and I'm trying to test how it works. Unfortunately, things goes as I'm not expecting. threads seems to execute in a not-parallel way. I've tried the sleep function but things stay the same.

The string "aa" does not printed until the thread dies !!! What should I do?

    class ThreadTest1 extends Thread {

    public void start() {
        for (int i=0; i<=100; i+=2) {
            System.out.println(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

class Test {

    public static void main(String[] args) throws InterruptedException {
        for (int i=0; i<50; i++) {
            Thread t1=new ThreadTest1();
            t1.start();
            System.out.println("aa");
        }
    }
}
  • 5
    You need to override `run` method not the `start` method. – Sandeep Singh Mar 09 '18 at 13:00
  • 4
    It's often better practice to avoid extending the `Thread` class and instead to create a class that `implements Runnable` and override the `run` method. Then create a thread with `Thread t1 = new Thread(new MyRunnable());`. – assylias Mar 09 '18 at 13:02

1 Answers1

1

Please see here for simple example: Defining and Starting a Thread

Basically - you need to implement 'run' method instead of start. and the thread will call run after starting it with start.

alex
  • 8,904
  • 6
  • 49
  • 75
Maciej
  • 1,954
  • 10
  • 14