Reputation: 5745
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
?
Upvotes: 0
Views: 101
Reputation: 206909
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.
Upvotes: 2