new Thread(Runnable runnableObj) Vs. extends Thread [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
I'm just wondering is there some subtle difference between creating your own custom object that extends Thread and creating a thread using the Thread(Runnable) constructor?
I have some code that works fine when I use classes that extend Thread, but if I try to use logic that creates Threads by using the Thread(Runnable) constructor the new threads do not seem to work properly - I can't detect that they are alive in the same way as when I use the custom sub-classes I made and they do not seem to end, ever.
In my code I'm just spawning a few threads then searching through my list of threads to find one that is alive and joining with it until it dies. Then I once again search for a thread in the list that is alive and join to it.. this continues until all threads die.
Thanks for reading.

A Thread is a resource for doing work. A Runnable is a piece of work. Are you creating a new type of resource, or just defining the work you want done?
To 'end' the thread you simply return from the 'run' method. Would need to see an example of your code to see what you mean about not being able to tell if they're active.
Creating Runnables also of course makes it easier to refactor your code to use a ThreadPool in the future.

In my code I'm just spawning a few threads then searching through my list of threads to find one that is alive and joining with it until it dies.
How (and why) are you "searching through my list of threads"? I would instead add the Thread to some sort of Collection that you then can then iterate across and join with each Thread in turn:
List<Thread> threads = new ArrayList<Thread();
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(new Runnable() ...);
thread.start();
threads.add(thread);
}
...
for (Thread thread : threads) {
thread.join();
}
Even better would be to use one of the ExecutorServices given by Executors. They have a lot of features around creating thread-pools and waiting for the pool to completely finish. Almost always recommended over new Thread(...).
I can't detect that they are alive in the same way as when I use the custom sub-classes I made
If you are trying to set the name of the Thread then you can't do this in the constructor of your Runnable. You can however do this in the run() method. You can do:
new Thread(new Runnable() {
public void run() {
Thread.currentThread().setName("...");
}
});
Otherwise, I'm not sure why you wouldn't be seeing your Thread unless it has already finished.
they do not seem to end, ever.
Using a Runnable, the thread finishes when the run() method returns -- either through a return or a throw. This is very much the same as extending Thread so I'm not sure why this wouldn't work.

I would really recommend to use the concurrency utility and not trying to manage yourself the Threads, which is complicated and error prone.
Using the concurrent api will also help you to apply the right patterns straight away.

Related

How to control threads liveness in Java?

There are two or more threads: main and several children. Children are workers, main controls children liveness. Once main thread detects a child thread is dead it creates new thread.
Currently I can't imagine better solution than checking t.isAlive() on each thread in a loop but it is well known that developers should avoid polling at any cost.
Note. Worker thread can wait several minutes on HTTP response (getInputStream() on URLConnection)
UPDATE
Worker doesn't finish its job but after it received a response or on timeout it creates new connection and awaiting for server response again.
You shouldn't use low level Thread methods if you don't really need them. Instead, use Java Concurrency API. For your case, I would use a thread pool which controls the threads. If a thread finishes its job, it returns to the pool rather than really dying.
According to the purposes in your question and our "dialog" in comments, I suggest you following simple idea.
if you want to recreate thread with same functionallity, why do you allow threads to die?
If you have, as you said, 3-d party threads implementation, you can wrap them into another thread and do not allow them to die.
Consider, 3-d party Thread implementation is called ThirdPartyThread class. So, instead of checking their state with .isAlive(), just wrap it into another thread with try ... catch:
new Thread(new Runnable() {
#Override
public void run() {
do {
try {
new ThirdPartyThread().run();
} catch (Throwable t) {
// you can vary behaviour here with different classes of exceptions.
// But main idea is to catch their death and go on
}
} while (true); // instead of `true` you can use your specific condition
}
}).start();
Andremoniy: if you want to recreate thread with same functionallity, why do you allow threads to die?
gumkins: For example I can't fix uncaught exceptions in third-party code.
If it doesn't make sense to catch the exception, and continue running in the same thread, then it won't make any sense to start a new thread to take the old thread's place. Starting a new thread accomplishes nothing.
All threads share the same heap and the same global state. If the library keeps global state in static variables or singleton objects, then that same state will be visible in every thread. If the global state is broken/invalid after some exception, then it's going to be invalid/broken in every thread. (And that includes any new threads that your program creates after the damage was done.)
Incidentally, the wheel that you are trying to re-invent here has a name: It's called a "thread pool."
The Java standard library provides a number of different kinds of thread pool which all implement the java.util.concurrent.ExecutorService interface. You should check it out.

regarding threads and runnables

I am having a problem understanding the differences between some kinds of making a tread loop.
one is (a rough demonstration):
Thread thread=new Thread("name") {
public void run()
{
// do stuff
}
}.start();
the second is:
making a class that imlpements runnable,
creating a thread :
Thread thread = new Thread(this,"name").start();
and the third (in android, i don't if it can work some how else):
making a Handler,
creating a Runnable,
and having handler.postDelayed(runnable), or handler.post(runnable).
I don't understand what's the difference, the only thing i did notice is that making a Thread makes the run loop work a lot faster than using a handler.
could some one explain to me what's the difference between them and what should i use to what?
The first and the second way are exactly the same. It is just different constructions that can be more useful in different situations. Note that Thread implements Runnable and may just run himself in the new thread.
The third way is a little bit misinterpreted by you. Handler runs Runnable in the thread where the Handler was instantiated (unless you specify another looper). If you created your Handler in the UI thread it will run Runnable in the UI thread as well. And as a result it may work slower.

Running a thread more than once

I have a Thread which runs my game loop. I want to be able to run this game loop each time I start a new game. But since the threads in Java can only be started once, how can I do this?
Create a new Thread around the same Runnable instance and start that.
Since you want the Thread that runs the game loop to keep running it, you need to code it something like this:
public class GameLoop implements Runnable {
...
public void run() {
while (gameNotFinished) {
// do stuff
}
}
}
If that is not working, then the chances are that the run() method is dying because of an exception that you are not catching / logging, and therefore not noticing.
1. When you say that "you need to run a thread", i means you want to start a sub-task on a separate thread.
2. Now if you mean this certain sub-task, then please prefer to run a new thread.
3. As you said But since the threads in Java can only be started once
This means that when a thread (thread of execution) completes its run() method, then the Thread object associated with it permanently looses its threadness, right....
But if this thread is from a pool, then the pool itself manages the Thread objects and its reused. Try using Executors from java.util.concurrent package.
1) The short answer is precisely what SLaks already said: just "...create a new thread around the same runnable instance and start that."
2) I think you might be confused about the distinction between the everyday meaning of "start", and the semantics of the Java Thread method "start()". This tutorial might help:
http://www.geom.uiuc.edu/~daeron/docs/javaguide/java/threads/states.html
3) Should you wish to re-use the same thread, you can use the methods "wait()" and "resume()":
http://www.javabeginner.com/learn-java/java-threads-tutorial

Multithreading java

I'm trying to figure out how to multithread in java. Right now, my program works fine with no concurrency but I want to implement multithreading to help speed it along.
The program runs several objects of a separate sub class and 50% of the time evaluation for each of those objects is spent in a process which only utilizes one core rather than the 8 available. These objects are completely independent of one another until but are used as inputs in the program.
I am trying to multithread this by having the subclass implement Runnable and then have my program use a thread for each such object. Would this be the correct way?
However, how are threads in java handeled? Would I need to dispose of the threads after each run? How does join work?
thanks
Don't manage threads manually, take a look at executors and thread pools in java
You're pretty much on track. You'll create a Thread object
Runnable r = new MyClassImplementingRunnable();
Thread t = new Thread(p);
t.start();
t.join(); // wait for thread to die
The Thread object is garbage collected like any other object, the thread itself dies when the run method completes. The key thing is that your Runnable's run method really must guarantee to return, your design cannot depend on being able to kill thread from the outside.
If you are going to have lots of threads you need to wait for them all to finish, so you can either keep a collection of the threads you've started and then use t.join( smallNumberOfMillis) to see which of them has finished. That's a little inefficient so there are other techniques for allowing threads to communicate with each other, I'd suggest reading this article about them.
#denis also mentions that the Executor and related classes provides a nicer abstraction above Threads. If you have an interest in learning the background then manually managing Threads is interesting. If you just want to get the job done, follow Denis' suggestion.
Take a look at http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
The constructor takes the number of threads you want. In this case the same as your number of cores.
ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(8);
List<Future> futures = new ArrayList<Future>();
foreach(...something...)
futures.add(s.submit(new MyCallable()));
foreach(Future f : futures)
f.get(); // Result of computation
System.out.println("Done");
This is a good way to start multithreading.
public class ThreadExample {
public static void main(String[] args) {
//Main thread
System.out.println("Main thread");
new Thread(new Runnable() {
#Override
public void run() {
//This thread is independent of the main thread
System.out.println("Inner Thread");
}
}).start();
}
}

Terminated Thread Revival

I am storing a bunch of threads objects in an arraylist. I want to be able to start these threads at random. Same thread can be started more than once. Before I start a thread object, I check on whether the thread is alive, and if they have either of NEW or TERMINATED status. This restriction because, I don't want to disturb the 'busy' threads. Now, for NEW threads, this works fine. But for TERMINATED thread, I get an exception.
When a thread ends, shouldn't it go back to being 'new'? Or are threads 'disposable' - like use once and done?
As it says in the documentation for Thread.start(), "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."
It is better for you to keep hold of Runnable instances and implement your own logic for keeping track of when the execution of each one of them finishes. Using an Executor is probably the simplest way to run the Runnables.
You should probably be using the awesome stuff provided in java.util.concurrent. Based on your description, ThreadPoolExecutor sounds like a good thing to check out.
This is the way I did it
class GarbageDisposalThread extends Thread {
public void start() {
try {
super.start();
} catch( IllegalThreadStateException e ) {
this.arrayList.remove(this);
this.arrayList.add( new GarbageDisposalThread( this.arrayList ));
}
}
private GarbageDisposalThread() {
}
public GarbageDisposalThread( ArrayList<Whatever> arrayList ) {
this.arrayList = arrayList;
this.start();
}
public void run() {
// whatever the code
}
private ArrayList<Whatever> arrayList = null;
}
that's it!
you can change the code according to your needs :P
Java threads cannot be restarted.
From the javadoc:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
See the Thread.start() javadoc for more information.
There are other ways to accomplish what you are trying to do. For example, you could use new Threads that continue the work that was done in the Thread that has finished execution. You may also want to investigate the java.util.concurrent package.
From another post...
You could use ThreadPoolExecutor, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.
So, you don't restart a thread, but you would redo/resume a task.

Categories