Majid Azimi
Majid Azimi

Reputation: 5745

Preventing other threads from running a piece of code

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

Answers (1)

Mat
Mat

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

Related Questions