防止其他线程运行一段代码

时间:2011-10-16 12:31:11

标签: java multithreading

我想阻止其他线程(非法线程)运行run()。解决方案是:

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 */ 
    }
}

MyThread班直接实施Runnable时,我们怎么能做同样的事情呢?

1 个答案:

答案 0 :(得分:2)

只需存储对Thread的引用,该引用可以作为Runnable类中的成员运行代码。在比较中使用它。