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
Threadthat is allowed to run the code as a member in yourRunnableclass. Use that in the comparison.