is this gud practice to create thread using runnable thread? - java

is thisgood practice to creating a new thread inside Runnable?
public class ExampleThread Implements Runnable{
public void run() {
try {
//Some functions
}
catch (IOException e) {
}
new Thread() {
public void run()
// some functions
}}.start();
}

It's kind of wrong in this case because ExampleThread is not really a thread, the first try catch block will be executed in the main thread.
Technically speaking, Runnable is just an interface so nothing wrong I guess.

Related

Only one thread appears to be active at once

I'm attempting to start another thread that branches from the main thread when thread.start() is called. But it appears to take the main thread in to the thread class. Here is minimum reproducible code of my issue. Thanks for looking.
public class Main {
public static void main(String[] args) throws InterruptedException {
ThreadWhileLoop threadWhileLoop = new ThreadWhileLoop();
//threadWhileLoop.run();
threadWhileLoop.start();
while (true){
Thread.sleep(1000);
System.out.println("Main Thread is doing its thing");
}
}
}
and here is the extended thread class
public class ThreadWhileLoop extends Thread {
#Override
public synchronized void start() {
super.start();
while (true){
System.out.println("ThreadWhileLoopIsRunning");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void run() {
super.run();
while (true){
System.out.println("ThreadWhileLoopIsRunning");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Expected output:
ThreadWhileLoopIsRunning
Main Thread is doing its thing
ThreadWhileLoopIsRunning
Main Thread is doing its thing
ThreadWhileLoopIsRunning
Main Thread is doing its thing
Actual output:
ThreadWhileLoopIsRunning
ThreadWhileLoopIsRunning
ThreadWhileLoopIsRunning
Don’t override start. The start method is used by the calling thread to get the new thread into a runnable state. There are very few good reasons to override it. In your posted code the whole program is running in the main thread.
What you need to do is override the run method in the new thread. Then have the main thread call start, which will cause the run method to execute in a separate thread.
(It would be better to create a Runnable than to override Thread. You can pass the Runnable into the Thread as a constructor argument. With this approach there is less temptation to tamper with the Thread object.)
You can check what thread is running with
System.out.println(Thread.currentThread().getName());
In another answer I have an example of starting a thread using a Runnable: https://stackoverflow.com/a/5915306/217324

thread of different class object in java

I have 2 java class "LegacyDAO" and "NewDAO" implementing Runnable. In an another class "Test" we create one object of each LegacyDAOObj and NewDAOObj.
Class Test {
public static void main(String args[]) {
LegacyDAO legacyDAOObj= new LegacyDAO();
NewDAO newDAOObj= new NewDAO();
Thread legacyDBThread= new Thread(legacyDAOObj);
Thread newDBThread= new Thread(newDAOObj);
}
}
Is there any relation between legacyDBThread and newDBThread ?
If I want newDBThread to execute some code and then wait for legacyDBThread to finish and then continue running. How can this be achieved ?
wait() and notify() API is helpful here. you can share some objects in two class and use wait-notify on these shared objects to sync two thread.
You can use countdown latch. Create a count down latch with count one, pass it to legacyDAOObj. After the logic executed in legacyDAOObj, count down the latch. Till the logic is executed in legacyDAOObj, newDAOObj awaits.
If you just want to wait for a thread to end, use Thread#join(), it seems to be the easiest way to achieve what you want.
CountdownLatch will be your best bet. Your newDaoObj will continue in main thread once legacyDaoObj finishes.
public static void main(String[] args) {
CountDownLatch start =new CountDownlatch(1);
LegacyDAO legacyDAOObj= new LegacyDAO();
NewDAO newDAOObj= new NewDAO();
new Thread(new Worker(legacyDAOObj)).start();
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
newDAOObj.doSomething();
}
public static class Worker implements Runnable{
LegacyDAO dao;
public Worker(LegacyDAO dao) {
this.dao = dao;
}
#Override
public void run() {
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
dao.doSomething();
start.countDown();
}
}

Thread and public void run() method in java [duplicate]

This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 9 years ago.
public Thread thread = new Thread();
public void start() {
running = true;
thread.start();
}
public void run() {
while(running) {
System.out.println("test");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
My problem is that the program will not print out "test" nor will it seem to loop despite 'running' being true. Is there a way I can continuously loop in the run method?
You haven't actually asked run() to be called. All you've done is declare a run() method unrelated to the Thread.
Put your run() method in a Runnable and pass that to the Thread.
public Thread thread = new Thread(new Runnable() {
public void run() {
while (running) {
System.out.println("test");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
The problem appears to be that you aren't running the run method that you think you're running in the thread.
First, you've created a Thread called thread. In your class's start method, you set running to true and call thread.start(). But that just calls Thread's run() method, which does nothing.
public void run()
If this thread was constructed using a separate
Runnable run object, then that Runnable object's run method is called;
otherwise, this method does nothing and returns.
You aren't calling your own run method.
You have created a run method. I can't see your class definition here, but I'm assuming that your class implements Runnable. You need to send an instance of your class as an argument to the Thread, by using the Thread constructor that takes a Runnable. Then the Thread will know to run your Runnable's run() method.
Well you need to call start() to start the thread. Otherwise neither running will be true
nor thread.start() get executed. Well i can guess you were intended to do something like this:
class MyTask implements Runnable
{
boolean running = false;
public void start() {
running = true;
new Thread(this).start();
}
public void run() {
while(running) {
System.out.println("test");
try {
Thread.sleep(1000);
// you were doing thread.sleep()! sleep is a static function
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new MyTask().start();
}
}

Calling non thread class from thread

My Problem:
I want to run a method from a Thread, which is no Thread but might take some time to execute (e.g. waiting for server response). It is important that my none thread method is in another class (the classes are Objects which are used in other classes too).
If you do this as in the example code, the whole program will pause for 10 seconds, but I want it to continue with other program code.
Is there a good way of doing this?
My code:
MyThread.java (extends Thread)
public Foo foo;
public void run() {
foo.bar();
}
Foo.java
public void bar() {
try {
Thread.sleep(10000);
// Represents other code that takes some time to execute
// (e.g. waiting for server response)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And a main method:
public static void main(String[] args) {
MyThread t = new MyThread();
t.foo = new Foo();
System.out.println("Starting!");
t.run();
System.out.println("Done!");
}
You don't want to call run() on the Thread, you want to call start().
Assuming MyThread extends Thread, you need to call start() not run().
Calling run() is just calling a method synchronously.
public static void main(String[] args) {
MyThread t = new MyThread();
t.foo = new Foo();
System.out.println("Starting!");
t.start(); // change here
System.out.println("Done!");
}
start() actually starts an OS thread to run your code on.
Use start() rather than run() on your thread. Or else it will be just like the main thread calling a method of another thread which means you are calling wait() on the main thread itself.
don't call run() method directly.
call start() method instead of run() method.
when call run() method directly
this thread go to main stack, and it run one by one.
class MyThread extends Thread{
public Foo foo;
public void run() {
foo.bar();
}
}
class Foo{
public void bar() {
try {
boolean responseCompleted = false;
boolean oneTimeExcution = false;
while(!responseCompleted){
if(!oneTimeExcution){
// Represents other code that takes some time to execute
oneTimeExcution = true;
}
if( your server response completed){
responseCompleted = true;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
System.out.println("Starting!");
t.start();
System.out.println("Done!");
}

Notify() from runnable

I have myThread.wait() that is in synchronzed(myThread) block. And I have Myrunner that implements runnable. I would like to tell notify() from myRunner, but it is not monitor object. Is it possible to get handle of myThread from myRunnable to make notify? Is there any other solution? Extend myRunnable from Thread and run it is not good for some reasons related on my code specific.
public class ThreadMain {
public Thread reader;
private class SerialReader implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(3000);
synchronized(this) {
System.out.println("notifying");
notify();
System.out.println("notifying done");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
ThreadMain() {
reader = new Thread(new SerialReader());
}
public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
synchronized(d.reader) {
try {
d.reader.wait();
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Both threads should synchronize using the same object. Also, you should really not use an existing object to syncronize, but create a object to be used explicitly for synchronization, like
Object lock = new Object();
Also see https://www.securecoding.cert.org/confluence/display/java/LCK01-J.+Do+not+synchronize+on+objects+that+may+be+reused
If the lock is to be used to interact with your thread, you can put it in the thread and provide a getter for anyone to use it.
To notify() a wait()ing thread you much have a reference to the object it is wait() on and you must be able to acquire a lock on it. I suggest you also change a state which notifying and you check that state change in a loop when wait()ing.
The only other option is to change the code of the waiting thread.

Categories

Resources