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?
You need to create NewThread instances rather than generic Threads for your code to execute:
new NewThread("F");
...
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");
Related
I am starting to learn threads. I have tried different types of thread creation. From the below code you can see the thread t4, target is new instance of Mythread1 & thread name is "Thread4".
But when I see the output I am not able to find the Thread name "Thread 4" instead I get the name "Thread-4". But this is a naming convention for a default thread name.
I am not able to understand what's wrong. I am sure its very basic mistake. Kindly correct me.
class MyThread1 extends Thread {
MyThread1() {
}
public MyThread1(String nameIn) {
super(nameIn);
}
public void run() {
System.out.println(this.getName());
}
}
class MyThread2 implements Runnable {
Thread ownThread;
public MyThread2() {
}
public MyThread2(String nameIn) {
ownThread = new Thread(this, nameIn);
}
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class ThreadCreation {
public static void main(String[] args) {
//Execution type1, as direct thread object
MyThread1 t1 = new MyThread1();
Thread t2 = new MyThread1();
Thread t3 = new Thread(new MyThread1());
Thread t4 = new Thread(new MyThread1(), "Thread4");
Thread t5 = new MyThread1("Thread5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
//Execution type2, pass the runnable object to thread constructor
Thread t11 = new Thread(new MyThread2());
Thread t22 = new Thread(new MyThread2(), "Thread22");
MyThread2 t33 = new MyThread2("Thread33");
t11.start();
t22.start();
t33.ownThread.start();
}
}
Output:
Thread-0
Thread-2
Thread-1
Thread-4
Thread5
Thread22
Thread-5
Thread33
But when I see the output I am not able to find the Thread name "Thread 4" instead I get the name "Thread-4". But this is a naming convention for a default thread name.
Your problem is in code like this:
Thread t4 = new Thread(new MyThread1(), "Thread4");
This code is using MyThread1 as a Runnable and not as a thread. So when the run() method is called you are then calling getName() on the MyThread1 instance and not on the thread that is actually running and calling your run() method and whose name is "Thread4". That is why the MyThread2 class works because it is using Thread.currentThread() to display the true running thread's name.
When you create a thread, either you need to extend Thread and start it as new MyThread1("Thread4") or implement Runnable and do new Thread(new MyRunnable1(), "Thread4");. Implementing of Runnable is the recommended pattern since it allows you to extend other classes.
You never want to do something like new Thread(new ClassThatExtendsThread(), "name"). That creates a fake Java Thread instance that is going to just confuse you.
In your MyThread1 you print the name of the thread object the method is in. Since you don't specify another name when creating the object, a sequential name "Thread-4" is generated for you.
You should either print the name of the executing thread, like in MyThread2, or create the MyThread1 object with a name:
Thread t4 = new Thread(new MyThread1("Thread4"));
i'm wondering what the code would look like in order to have a program which creates a loop on start. This loop then creates several, thread objects all on their own threads so their all running at the same time, and they all run the same code. Is there a way to do this? as in for example we make 2 threads, they never stop looping and one is always prinintg "thread 1" and 1 is always printing "thread 2" at the same time. This is what i'm wondering. Thanks in advance!
class MyTask implements Runnable {
public static id = 0;
public MyTask(){
id++;
}
public void run(){
while(true){
System.out.print("Thread " + id);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Generator{
Public static void main(String[] args){
Runnable[] myTasks = new Runnable[2];
myTasks[0] = new MyTask();
myTasks[1] = new MyTask();
for(Runnable r: myTasks){
Thread t = new Thread(r);
t.start();
}
}
}
I didn't compile it. but this is how you are going to do.
When you run class Generator, two Threads will start, and they will print Thread 1. and thread 2 once every one second forever.
I'm new to threads. I wanted to create some simple function working separately from main thread. But it doesn't seem to work. I'd just like to create new thread and do some stuff there independently of what's happening on main thread. This code may look weird but I don't have much experience with threading so far. Could you explain me what's wrong with this?
public static void main(String args[]){
test z=new test();
z.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.add(z);
frame.addKeyListener(z);
frame.setVisible(true);
one=new Thread(){
public void run() {
one.start();
try{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v){System.out.println(v);}
}
};
}
You are calling the one.start() method in the run method of your Thread. But the run method will only be called when a thread is already started. Do this instead:
one = new Thread() {
public void run() {
try {
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v) {
System.out.println(v);
}
}
};
one.start();
You can do like:
Thread t1 = new Thread(new Runnable() {
public void run()
{
// code goes here.
}});
t1.start();
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start().
The result is a new instance of class Thread, which is called join().
You need to do two things:
Start the thread
Wait for the thread to finish (die) before proceeding
ie
one.start();
one.join();
If you don't start() it, nothing will happen - creating a Thread doesn't execute it.
If you don't join) it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
Since a new question has just been closed against this: you shouldn't create Thread objects yourself. Here's another way to do it:
public void method() {
Executors.newSingleThreadExecutor().submit(() -> {
// yourCode
});
}
You should probably retain the executor service between calls though.
There are several ways to create a thread
by extending Thread class >5
by implementing Runnable interface - > 5
by using ExecutorService inteface - >=8
If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.
Try this, which will help you to call as many times you needed.
It will be helpful when you need to execute your run more then once and from many place.
class A extends Thread {
public void run() {
//Code you want to get executed seperately then main thread.
}
}
Main class
A obj1 = new A();
obj1.start();
A obj2 = new A();
obj2.start();
run() method is called by start(). That happens automatically. You just need to call start(). For a complete tutorial on creating and calling threads see my blog http://preciselyconcise.com/java/concurrency/a_concurrency.php
A simpler way can be :
new Thread(YourSampleClass).start();
Please try this. You will understand all perfectly after you will take a look on my solution.
There are only 2 ways of creating threads in java
with implements Runnable
class One implements Runnable {
#Override
public void run() {
System.out.println("Running thread 1 ... ");
}
with extends Thread
class Two extends Thread {
#Override
public void run() {
System.out.println("Running thread 2 ... ");
}
Your MAIN class here
public class ExampleMain {
public static void main(String[] args) {
One demo1 = new One();
Thread t1 = new Thread(demo1);
t1.start();
Two demo2 = new Two();
Thread t2 = new Thread(demo2);
t2.start();
}
}
class cc extends Thread {
cc(String s) {
super(s);
}
}
class mainn {
public static void main (String args[]) {
cc t1 = new cc("first");
t1.start();
}
}
Question: Is the thread born
at this point --> cc t1 = new cc("first");
or is it born and started at this point --> t1.start();?
"Born" is not a formal term that I've seen before in Java, relating to threads.
The Thread object is constructed/instantiated/created when you call new cc("first").
The thread itself is started when you call t1.start(). It still exists before then, but is not running, and will not be scheduled by the operating system.
(P.S. Java naming conventions are that class names start with capitals - it is surprisingly confusing to read code that violates this. new cc(...) jumps out at me as somehow wrong.)
Thread is born at this point ?--> cc t1 = new cc("first");
At this point thread is in New state which is not alive
t1.start();
Here your thread is alive but may be in Running/Runnable state.
Refer below Java Doc for all States.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html
Example
public static void main(String[] args) {
Thread t1=new Thread(new Runnable() {
#Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("running");
}
}
});
System.out.println(t1.isAlive());
t1.start();
System.out.println(t1.isAlive());
}
Which prints :
false
true
running
If your word "born" creation of new thread object, then it is when you call
new cc("first")
But a thread process will be forked only you start a thread using
t1.start()
and it is when actually ready to run in path of execution from the calling thread.
- At this line cc t1 = new cc("first"); The Thread Object will come into existence.
- At this line t1.start() the toe (thread of Execution) will be created and assigned a Runtime Stack.
Poorly written question but the answer is that it is born at t1.start(); stage.
Supposed I have a class MyThread, which implements Runnable with a method dosomething():
class MyThread implements Runnable{
Object dosomething(Parameter p){ ... }
run(){...};
}
If I do:
main(){
MyThread my = new MyThread().run();
Object o = my.dosomething(p);
}
will dosomething be executed on myThread or in the main Thread?
How can I start the execution of dosomething on myThread from the main Thread and retrieve the returned Object?
main(){
MyThread my = new MyThread().run();
Object o = my.dosomething(p);
}
If you do that it won't compile: you're trying to assign the result of a void method, void run(), to an object of type MyThread.
Implementing runnable and calling run() will not cause the code to be executed in a separate thread unless you pass it to another thread (i.e. Tread t = new Thread(my);)
How can I start the execution of dosomething on myThread from the main Thread and retrieve the returned Object?
You do that by storing the result of doSomething() in a location where you can access it later.
class MyClass
{
public Object doSomething()
{
// return the object
return new Object();
}
}
class MyRunnable implements Runnable
{
private final MyClass _mc;
private final object _lock;
private final List<object> _results;
public MyRunnable(MyClass mc, List<object> results, object lock)
{
_mc = mc;
_lock = lock;
_results = results;
}
public void run()
{
synchronized(_lock)
{
_results.add(_mc.doSomething());
}
}
}
So now in main:
void main(){
MyClass mc = new MyClass();
List<object> results = new List<object>();
object lock = new object();
// Execute your thread and wait for it to complete
Thread t = new Thread(new MyRunnable(mc, results, lock ));
t.start();
t.join();
// Get the results
for(object result:results)
{
// do something with the result
}
}
This should give you an idea of what you're doing "wrong." A more realistic example would be if you spawn multiple threads, run them concurrently and then join on all of them until they all complete.
Sounds like you may want to consider Callables and Futures.
There's a decent explanation at http://www.vogella.de/articles/JavaConcurrency/article.html#futures
You can use delegate, for example.
new MyThread(callWhenFinishObject)
It'll be executed on the main thread, since it's that thread that calls the method. If you want dosomething to run in the separate thread, have it called within run() and store the result in a myThread field for later retrieval.
You might want to check class Future or other stuff in java.util.concurrent for some convenient way of waiting for the result to become available.
EDIT: if dosomething should only run until some condition is satisfied that must be flagged in the main thread, have run() block until the main thread somehow signals the other thread that it's okay to go on.
EDIT 2: here, someone confirm this is what's being asked:
package threadtest;
public class Main {
public static void main(final String[] args) {
final MyThread otherThread = new MyThread();
System.out.println("Main thread: I'm gonna start the other thread now...");
otherThread.start();
System.out.println("Main thread: there, hope it does well.");
try {
Thread.sleep(1000); //Lets main thread take a snooze...
} catch(InterruptedException ex) {
//whatever
}
System.out.println("Main thread: I'm gonna do some stuff in the meantime...");
try {
Thread.sleep(200); //Lets main thread take a snooze...
} catch(InterruptedException ex) {
//whatever
}
System.out.println("Main thread: maybe clean up the kitchen.");
try {
Thread.sleep(1000); //Lets main thread take a snooze...
} catch(InterruptedException ex) {
//whatever
}
System.out.println("Main thread: does other thread have something for me yet?");
if(otherThread.getResult() == null)
System.out.println("Main thread: nope, not yet.");
try {
Thread.sleep(500); //Lets main thread take a snooze...
} catch(InterruptedException ex) {
//whatever
}
System.out.println("Main thread: oh crap! I forgot to tell it that it may execute its method!");
otherThread.allowToExecute();
System.out.println("Main thread: phew... better keep checking now before it gets angry.");
while(otherThread.getResult() == null) {
try {
Thread.sleep(100); //Lets main thread take a snooze...
} catch(InterruptedException ex) {
//whatever
}
}
System.out.println("Main thread: there we go, it gave me a result. Rest in peace, other thread...");
}
private static class MyThread extends Thread {
private boolean mayExecuteDoSomething = false;
private Object result = null;
#Override
public void run() {
System.out.println("Other thread: whoa, someone started me!");
while(!mayExecuteDoSomething) {
try {
Thread.sleep(100); //I'm gonna sleep for a bit...
} catch(InterruptedException ex) {
//whatever
}
}
System.out.println("Other thread: alright, I'm allowed to execute my method!");
result = doSomething();
System.out.println("Other thread: there, did it. I'll just call it quits now.");
}
public void allowToExecute() {
mayExecuteDoSomething = true;
}
private Object doSomething() {
return new Object();
}
public Object getResult() {
return result;
}
}
}
This is a very crude approach to the issue. The basic concepts are there, though. In reality, you'd want to use stuff like Callable and Future for proper asynchronous computation.
That is not possible.
When you create a thread, it runs the code in run() and exits.
There is no way to inject code into a different thread; that would break the core execution model. (Within a thread, your code runs sequentially, with nothing in between)
If you want to, you can create a thread that listens for callback (Runnable instances) in a queue and executes them (like a message loop).
This is how the UI thread works.
Also, you aren't actually startign a thread; you need to write new Thread(someRunnable).start()