我有一个方法和一个线程,我想按以下顺序运行:首先该方法应该对对象执行某些操作,然后线程应该对该对象执行某些操作。他们共享同一个对象。我必须同步它们,但我只是在与线程会面。我怎样才能做到这一点?
private synchronized method()
{
//do something with an object (a field)
}
Runnable ObjectUpdater = new Runnable()
{
//do something with the object after the method has finished
}
我的代码,以某种方式设法卡住我的主线程(方法所在的位置) 我的线程代码:
private Runnable something = new Runnable(){
synchronized (this){
while (flag == false)
{ try {wait();)
catch (IntExc ie) {e.printStackTrace...}
}
//here it does its thing
}
setFlag(false);
}
My method code (part of the main thread)
private void Method()
{
//do its thing
setFlag(true);
notifyAll();
}
最佳答案
对我来说这是简单的问题
" you said that I do not know which is going to access the object first - the separate ObjectUpdater thread, or the main thread (with the method). If the separate thread accesses it before the main thread, that is bad and I don't want this to happen"
如果你想让主线程方法先调用然后objectUpdater线程,有一个标志来知道该方法是否首先被主线程访问,如果是updater则调用wait到该线程,一旦main完成它调用notify这将运行分隔线, 要知道哪个线程是主线程或更新线程,请在创建线程时为其设置名称。并获取名称 Thread.currentThread().getName()。
关于java - 将线程和方法与对象同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3759374/