'Merging three threads in Java
I am trying to create few flows in java, my program must to create 3 threads and 1 main thread, and than stop.
I 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 program?
Solution 1:[1]
You need to create NewThread
instances rather than generic Threads
for your code to execute:
new NewThread("F");
...
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
use following in public static void main
:
NewThread th1 = new NewThread ("F");
NewThread th2 = new NewThread ("S");
NewThread th3 =new NewThread ("T");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ryan Stewart |
Solution 3 | hbk |
Solution 4 |