Question

im just a begginers and try to learn Java

Target - try to create few flows in java, my program must to create 3 flows and 1 main flow, and than stop.

Whats done:

Created class with implemented Runnable

class NewThread implements Runnable {
String name;
Thread t;

NewThread(String threadname){
    name = threadname;
    t = new Thread (this, name);
    System.out.println(t);
    t.start();
}

public void run (){
    try {
        System.out.println("111");// why cant see it?
        Thread.sleep(1000);
    }
    catch (InterruptedException e){
        System.out.println(e);
    }
    System.out.println("End Thread");
}

And main:

 public class ThreadDemo {
 public static void main (String []args){
    new Thread ("F");
    new Thread ("S");
    new Thread ("T");

    try {
        Thread.sleep(10000);
    }
    catch (InterruptedException e){

    }
    System.out.println("End M");
}
}

I think i will get result like 3 string of 111 and one string End M -

111
111
111
End M

but i get just

 End M

Can anyone say why i dont get 3 string in result of my programm?

many thanks to all.

Was it helpful?

Solution

You need to create NewThread instances rather than generic Threads for your code to execute:

new NewThread("F");
...

OTHER TIPS

new Thread ("F"); creates a new Thread object named "F", which isn't the same as one of your NewThread objects. You never create any of those, so you shouldn't expect any of their code to run. Also, it's very unusual to create a Thread inside of a Runnable. Instead, you should create a Runnable, then create a Thread to hold your Runnable and start() the Thread. The Java Concurrency tutorial might help clear things up for you.

Find my mistake

I must to write

public static void main (String []args){
    new NewThread ("F");
    new NewThread ("S");
    new NewThread ("T");

instead of

 new Thread ("F");

Now its ok.

use following in public static void main:

NewThread th1 = new NewThread ("F");
NewThread th2 = new NewThread ("S");
NewThread th3  =new NewThread ("T");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top