Java - creating a new thread - java

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();
}
}

Related

Recursive calling of run method due to Thread.currentThread().run()

i am new to multithreading and trying to clear my basics.
public class SleepExample extends Thread {
private int counter = 0;
#Override
public void run() {
try {
counter++;
System.out.println("Value of counter "+counter);
System.out.println("Thread going in sleep "+Thread.currentThread().getName());
Thread.currentThread().run();
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread out of sleep "+Thread.currentThread().getName());
}
public static void main(String[] args) {
new SleepExample().start();
new SleepExample().start();
Test test = new Test();
Thread t = new Thread(test);
t.start();
}
}
//another class implementing runnable
public class Test implements Runnable {
#Override
public void run() {
System.out.println("In Test runnable method");
}
}
When i run this code, my run method of SleepExample recursively call itself after below line
Thread.currentThread().run();
for thread belonging to SleepExample (Thread -0, Thread -1) and
it goes to run method of Test class for thread t.
I am unable to understand the usage of Thread.currentThread().run();
P.S. - I read its java doc and so i have implemented a runnable
I am unable to understand the usage of Thread.currentThread().run();
You are not supposed to call it directly. From Thread.start() You are supposed to use start() to call run() and that is it.
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
You are already running in the run() so you should only call this if you can say why you are doing it, even then it will look like a bug or be plain confusing and I would suggest you use a loop instead.
When i run this code, my run method of SleepExample recursively call itself after below line
You have a method calling itself, so you should expect that to happen. There is nothing special to Thread in this regard. It is like any other recursive call in a method.

Why thread cannot update the ArrayList field?

My structure looks like :
public class ReadCSV {
volatile List<FlightDetails> detail;
main() {
ReadCSV obj=new ReadCSV();
obj.detail=Collections.synchronizedList(new ArrayList<FlightDetails>());
new Thread(new Runnable(){
#Override
public void run() {
try {
...
//pass the object along
readAndParseFile("someFile.csv",obj);
} catch (IOException e) {
...
}
// prints Alright
System.out.println(obj.detail.get(0).getDep_loc());
}
}).start();
// Throws AIOB Exception
System.out.println(obj.detail.get(0).getArr_loc());
}
static void readAndParseFile(String csvFileName, ReadCSV obj) {
...
..
//make changes to the object
obj.detail.add()
// works fine
}
While passing the object without the thread, the changes are made.But the changes are not reflected even after making the field Volatile.
1) what is wrong in the above code?
2) Is it alright to follow this approach?
3) what is the general way to do such jobs?
I am very new to multi threading .
If you have a Thread object that does some task and you want to see the results, wait for its termination.
Thread p = new Thread(new Runnable(){
//...
}); // no start here
p.start(); // let it run
p.join(); // wait for its end
There is not much gain in executing another thread while the starting thread has nothing better to do than to wait for the started thread's end.
you need to wait till your reader thread has finished.
you can use futures or Thread.join()

Why pass "this" to Thread constructor?

"this" is used to refer to the members of the current class. I was trying a program in java using multithreading.
this => object of the current class where it is referred
The program is
class Thread_child implements Runnable{
Thread t;
Thread_child()
{
t = new Thread(this,"DemoThread");
System.out.println("ChildThread:"+t);
t.start();
}
public void run(){
char a[] = {'A','B','C','D','E','F','G','H','I','J'};
try{
for(int i=0;i<10;i++){
System.out.println("ChildThread:"+i+"\t char :"+a[i]);
Thread.sleep(5000);
}
}
catch(InterruptedException e){
System.out.println("ChildThread Interrupted");
}
System.out.println("Exiting from the Child Thread!");
}
}
class Thread_eg{
public static void main(String args[]){
new Thread_child();
try{
for(int i=1;i<=10;i++){
System.out.println("MainThread:"+i);
Thread.sleep(3000);
}
}
catch(InterruptedException e){
System.out.println("MainThread Interrupted");
}
System.out.println("Exiting from the Main Thread!");
}
}
What does this Thread() constructor do . why do we need to pass 'this' as a parameter to it. I tried to run it without giving the parameter but the child threads were not run.only the mainthread was printed . when i replaced the thread constructor with the parameter it ran the child threads. why is that so?
Have a look at the documentation for that constructor, and all should become clear. Pay particular attention to the part that states
If the target argument is not null, the run method of the target is called when this thread is started. If the target argument is null, this thread's run method is called when this thread is started.
(The underlying issue is that a Thread is just a thread, and doesn't inherently do anything. You need to tell it what to execute.)
Because this is the Runnable object (Thread_child) whose run() method gets called.
There are two ways of implementing a Thread. One is create a class that extends Thread class and this class runs as a thread in VM.
MyThread mt = new MyThread();
mt.start();
The start will result in execution of run method that was overridden from Thread.
In case you could not extend to Thread, you can implement Runnable which makes you implement run method. Now to run this class you need to pass an object of it to Thread.
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr); // telling the thread what needs to be execute through run method
t.start();
In your code since you are starting thread in constructor, you have passed this instead my mr in above example. Basically you need to tell Thread what it needs to do via run method.
This is how run of Thread looks like:
public void run() {
if (target != null) { //target is nothing but a Runnable.
target.run();
}
}

Trigger thread's method by another thread in Java

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()

Thread.sleep pausing whole program

I have a main form with a button, that when pressed, should start a new count-down timer thread.
This is the code in the button's action listener:
Counter c = new Counter(timeToFinish);
This is the code for the Counter class:
class Counter implements Runnable {
int waitingTime = 0;
Thread myCounter = new Thread(this);
public Counter(int waitingTime)
{
this.waitingTime = waitingTime;
myCounter.run();
}
public void run(){
//Start countdown:
do
{
waitingTime -= 1;
try {
Thread.sleep(1000);
System.out.println(waitingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (waitingTime >= 0);
}
}
The problem is, when I create a new instance of the Counter class, it pauses the whole program, not just that thread! The problem must be with "Thread.sleep".
Because you are directly calling the run method.
Instead you should wrap it in a Thread and start the thread.
For e.g., replace
myCounter.run();
by
new Thread(this).start();
Just because you call the run method from the Counter constructor. That's not how it works with threads. You'll have to remove this call, wrap the Runnable in a Thread instance and call start() on the thread:
new Thread(new Counter(2)).start();
You aren't actually start()ing multiple threads.
The Thread.run() method simply runs the code associated with the thread, like any other normal function. It doesn't start a separate thread.
You need to call Thread.start(), to start a new thread and run your code in it.
You should use start() method of your thread. Use
c.start();
otherwise you have a class and you are invoking one of its methods, and of course it is running in main thread and sleeping the main thread.
You're calling run directly, it'll run in the current thread, and sleep the current thread, which I guess is the event thread. This cause the pause in your program.
You should use SwingUtilities class
see
http://www.java2s.com/Code/Java/Threads/InvokeExampleSwingandthread.htm
// Report the result using invokeLater().
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resultLabel.setText("Ready");
setEnabled(true);
}
});
}
};

Categories

Resources