I want to prevent to other threads(illegal threads) from running run(). the solution is:
public class MyThread extends Thread {
public void run() {
if (currentThread() != this)
throw new IllegalStateException("Exception occurred by: " + currentThread().toString());
/* Here goes the main logic of thread */
}
}
How could we do the same thing when MyThread class is directly implementing Runnable?
Simply store a reference to the Thread that is allowed to run the code as a member in your Runnable class. Use that in the comparison.
Related
What is happening in the background if I do this:
class TestThread {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
System.out.println(t.getName());
}
}
I know that to create a new thread you must override the run() method by either extending the Thread class or by implementing the Runnable interface.
If we implement the Runnable interface we have to provide the target run method where the code which has to run concurrently is provided.
Also, If we do not override the run() method and do not extend the Thread or implement the Runnable, the main() thread will execute.
I would like to know as to what exactly will happen in the background when I execute the above code? Does the main have a run() method like other Threads? Will this create a new Thread in addition to the main thread?
/**
* 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.
*
* Subclasses of Thread should override this method.
*/
public void run() {
if (target != null) {
target.run();
}
}
Since you haven't set a Runnable target, nothing will happen.
Does the main have a run() method like other Threads?
Low-level API can be used for this purpose. They don't necessarily need to create a Thread instance to run a thread. Here is a good discussion: How main thread created by Java?
The new thread is created, starts, executes an empty* method, and terminates.
*) not really empty:
public void run() {
if (target != null) {
target.run();
}
}
I am pretty new to using multithreading, but I want to invoke a method asynchronously (in a separate Thread) rather than invoking it synchronously. The basic idea is that I'm creating a socket server with an object in memory, so for each client I will have to run something like object.getStuff() asynchronously.
The two constructs I found were:
having the class implement Runnable and threading this and
declaring a runnable class within a method.
Additionally this method needs a return value- will it be necessary to use Executor and Callable to achieve this? Could someone point me in the right direction for implementing this?
I have tried implement option 2, but this doesn't appear to be processing concurrently:
public class Test {
private ExecutorService exec = Executors.newFixedThreadPool(10);
public Thing getStuff(){
class Getter implements Callable<Thing>{
public Thing call(){
//do collection stuff
return Thing;
}
}
Callable<Thing> callable = new Getter();
Future<Thing> future = exec.submit(callable);
return future.get();
}
}
I am instantiating a single test object for the server and calling getStuff() for each client connection.
Threading Tutorial
The Java tutorial on concurrency has a good section on this. It's at https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html. Essentially, you can either implement Runnable or Callable, or inherit from Thread.
Subclassing Thread
You can write a class, including an anonymous inner class, that extends Thread. Instantiate it, then invoke the start() method.
public class MyThread extends Thread {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
}
}
Implementing Runnable
You can write a class that implements Runnable, then wrap an instance in a Thread and invoke start(). Very much like the previous.
public class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
(new Thread(r)).start();
}
}
Return Value
Runnable doesn't allow for return values. If you need that, you need to implement Callable instead. Callable looks a lot like Runnable, except you override the call() method instead of the run() method, and you need to give it to an ExecutorService.
public class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println("A thread using Callable<Integer>");
return 42;
}
public static void main(String[] args) {
MyCallable c = new MyCallable();
Future<Integer> f = Executors.newSingleThreadExecutor().submit(c));
System.out.println("The thread returned: " +
f.get());
}
}
The two constructs I found were 1) having the class implement Runnable and threading 'this' and 2) declaring a runnable class within a method.
Option (2) probably is better. Most programs would be improved if they had more classes, not fewer. Each named entity in a program—each package, class, method, whatever—should have just one responsibility. In your option (1), you are asking the class to do two things.
For your option (2), you don't actually have to declare a whole class. You can either use an anonymous inner class, or if you can go with Java8 all the way, you can use a lambda expression. Google for either one to learn more.
Additionally this method needs a return value.
The classic way, is for the Runnable object to return the value through one of its own fields before the thread terminates. Then the parent thread, can examine the object and get the return value afterward.
Will it be necessary to use Executor and Callable to achieve this?
Necessary? A lot of people think that ExecutorService is a Good Thing.
Sounds like you are creating a server that serves multiple clients. Do these clients continually connect and disconnect? The advantage of using a thread pool (i.e., ThreadPoolExecutor) is that it saves your program from continually creating and destroying threads (e.g., every time a client connects/disconnects). Creating and destroying threads is expensive. If you have a lot of clients connecting and disconnecting, then using a thread pool could make a big difference in the performance of your server.
Creating and managing threads by yourself is generally bad approach.
As you already pointed - use Executors utility class to create executor and submit Callables to it.
public class RunWResult implements Runable{
private volatile ResultType var;
//the thread method
public void run(){
...
//generate a result and save it to var
var = someResult();
//notify waiting threads that a result has been generated
synchronized(this){
notify();
}
}
public ResultType runWithResult(){
//run the thread generating a result
Thread t = new Thread(this);
t.start();
//wait for t to create a result
try{
wait();
}catch(InterruptedException e){}
//return the result
return var;
}
}
Can anyone explain to me why the first thread doesn't work and the second works perfectly:
public class Test {
public static void main(String args[]) throws InterruptedException {
TestThread1 t1 = new TestThread1();
TestThread2 t2 = new TestThread2();
t1.startThread();
t2.start();
Thread.sleep(4000);
t1.stopThread();
t2.stopThread();
}
}
class TestThread1 extends Thread {
private volatile TestThread1 thread;
public void startThread() {
thread = new TestThread1();
thread.start();
}
public void run() {
while (thread != null) {
System.out.println("RUNNING 1 ...");
}
}
public void stopThread() {
thread = null;
}
}
class TestThread2 extends Thread {
private volatile boolean finished = false;
public void run() {
while (!finished) {
System.out.println("RUNNING 2 ...");
}
}
public void stopThread() {
finished = true;
}
}
When I debug inside TestThread1 class: Inside startThread, the thread member is filled (so it is not null), inside run, thread member is null!!! And finally, inside stopThread, the thread member is not null!!!
Can anyone explain to me what is happening here?
Here, you have two instances of TestThread1 t1:
One is stored into your t1 local variable (in your main method).
One is stored into your thread instance variable (of t1).
t1 is never started, t1.thread is.
t1.stopThread() sets t1.thread to null, but it doesn't affect t1.thread.thread.
Since you're starting t1.thread, its run method is using t1.thread.thread:
This is never set to anything (so it's using null).
Calling t1.stopThread() like you do would only set t1.thread to null, which wouldn't affect t1.thread.thread.
More generally, you can't just "kill" a thread as such, but you can implement tests within the method to tell it to return under certain circumstances. What you've done with your second test is closer to this (using while (!finished) { ... } with a volatile variable).
I wouldn't limit the test to finished. It's also useful to test whether the thread was interrupted, in particular because if you run your runnables within an ExecutorService shutdownNow() will try to interrupt them (see this question).
I'd use while (!finished && !Thread.currentThread().isInterrupted()) { ... }.
(Note the difference between Thread.currentThread().isInterrupted() and Thread.interrupted(): they may seem similar, but the latter will also reset the status, which you might not want.)
Depending on what's within your loop (or whether there is a loop at all), you may want to use something like if (finished || Thread.currentThread().isInterrupted()) { return; } at various strategic points, where it makes sense.
There is two TestThread1 object being created, one is started and the other is stopped.
I suggest not extending Thread and instead wrapping your Runnable once.
TestThread1 t1 = new TestThread1();
t1.startThread();
This will simply call method startThread() on object t1. Inside this method you are creating a new Thread.
thread = new TestThread1();
thread.start();
But for this Thread thread instance variable is null(It is not null for t1).
So in both cases thread variable should be null.
Because in your main method you create a Thread1 Object. You then run startThread which creates a different Thread1 object inside the first one and sets it to the field thread. You then start the second object which didn't have its own thread field initialized. When run method is run on the second object the condition is false and the while loop doesn't start.
Your object hierarchy looks something like this
t1 (Thread1) {
thread(Thread1): {
thread: null;
run() {
while (thread != null) {...} // this is the method that is run - thread is null here since you never initialized it
}
};
startThread() {} // calls the run method on the nested thread object above
run() {
while (thread != null) {...} // this method is not run since t1.start() is never called in main()
}
}
in your case,
t2.start();
is calling run method directly, it is not creating thread inside startThread method.
so t1.stopThread() makes the volatile thread inside Thread1 class null. so you are getting like that.
solution
use
t1.startThread();
t2.startThread();
instead of
t1.startThread();
t2.start();
which makes 2 threads to create separate threads inside that method.
if you want a single thread of Thread1 then use runnable interface and create 2 threads and call startThread respectively rather than creating extra threads inside main.
How can I write a method of a class implementing the Runnable interface (started from an ExecutorService) that would interrupt the thread?
I know that I can use Future fut = es.submit(foo); (where es is the ExecutorService and foo is an instance of my class) and then call fut.cancel(true); from inside the main function of the application, but how do I call something like that from inside the class itself?
I would like to have in my Runnable class a method
public void stop() {…}
so that I can call foo.stop() from anywhere (including from the main function of the application) and it will work as if I had used the Future.cancel function (it has to raise ÌnterruptedException` if the thread is awaiting to acquire a Semaphore).
public class MyRunnable implements Runnable {
private Thread currentThread;
#Override
public void run() {
currentThread = Thread.currentThread();
// Do here something interruptible
}
public void interrupt() {
if (currentThread != null)
currentThread.interrupt();
}
}
But as it has been said, it's bad architecture since you're mixing responsibilities of WHAT is being done (Runnable) with HOW it's being done (execution)
You can create your own class the implements Runnable and also another interface:
public interface StoppableRunnable extends Runnable {
public void stop();
}
And use this type of Runnable which is guaranteed to have a stop() method which you can call.
Example of use:
public MyRunnable implements StoppableRunnable {
private volatile boolean stopped = false;
public void run() {
while(!stopped) { // Do something.... }
}
public void stop() {
stopped = true;
}
}
What you want to do - implementing a stop() method inside a Runnable - may actually introduce some confusion in the structure of your code. Why? A Runnable object is, by design, something which holds the code that has to run. But adding a stop() method would go beyond the sole responsibility of a Runnable object: that is, you will make it able to control the execution of your code. That should be avoided.
Here is a hint: there is no start() method in Runnable. Indeed, there is one in the Thread class, and the Runnable interface has been introduced in the JDK to reduce coupling between the "runnable" code and the object which controls its execution (an instance of Thread).
My question is: why aren't you satisified with the future.cancel()? Could you please add some precisions in your design requirements?
As far as my understanding is so far; a class which implements runnable seems to only be able to perform one set task within its run method. How is it possible to create a new thread and then run different methods from this one additional thread, without needing to create some new runnable class for every set task.
Make your own subclass of Thread (MyThread extends Thread)
Add private members to control the behavior.
Add bean-pattern get/set methods to control the private members, or use a fluent API.
Read this properties in the run() method.
MyThread t = new MyThread();
t.setTypeOfSparrow("African");
t.setFavoriteColor("Yellow");
t.start();
Your Runnable class can call any logic it likes. The logic you want to run must be in some class, could be different methods of the Runnable class or could be in lots of other classes.
How did you plan to tell the runnable what to do?
You could do something like:
MyRunnable implements Runnable {
private String m_whatToDo;
public MyRunnable(String whatToDo) {
m_whatToDo = whatToDo;
}
public void Runnable run() {
if ("x".equals(m_whatToDo) {
// code to do X
} else if ( "y".equals(m_whatToDo) {
// code to do Y
} else {
// some error handling
}
}
}
Or as Srikanth says you could communicate the intent by other means such as thread names.
However I don't see much overhead in creating a runnable class. Just adding a public void run() to a class is surely not that big a deal?
A class should perform one task and perform it well, and if you are adding multiple operations in a single Runnable then you are violating this principle. You should create a new implementation of Runnable for each runnable task.
To simplify your api you might like to create a MyRunnableFactory method which constructs a runnable class depending on one or more construction criteria. This would shield the user from having to remember which class to create for each task.
Your question isn't quite clear. My guess is that you want to run different methods in some other thread, but you don't want to waste time restarting a new thread for each method. In that case you need an ExecutorService with one thread. You can submit sequentially some Runnables to a thread that is kept alive between calls.
Or more simply if you already know the order in which your methods are called
(new Thread() {
#Override public void run() {
method1();
method2();
...
}
}).start();
In the run() method check for the thread name and call the appropriate method.
public class SampleThread implements Runnable{
/**
* #param args
*/
Thread t=null;
public SampleThread(String threadName)
{
t=new Thread(this,threadName);
t.start();
}
#Override
public void run() {
if(t.getName().equals("one"))
{
One();
}
else if(t.getName().equals("two"))
{
Two();
}
}
public void One()
{
System.out.println(" ---- One ---- ");
}
public void Two()
{
System.out.println(" ---- Two ---- ");
}
public static void main(String[] args) {
SampleThread t1=new SampleThread("one");
SampleThread t2=new SampleThread("two");
}
}