java - 将线程和方法与对象同步?

标签 java multithreading

我有一个方法和一个线程,我想按以下顺序运行:首先该方法应该对对象执行某些操作,然后线程应该对该对象执行某些操作。他们共享同一个对象。我必须同步它们,但我只是在与线程会面。我怎样才能做到这一点?

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/

相关文章:

multithreading - 如何使用多线程提高性能?

java - 在java中设置方法的运行时间限制

c++ - boost::asio 中的 post 和 dispatch 有什么区别?

c# - 任务重复?

java - 使用 Jakarta HttpClient 模拟 POST 网络请求

python - 对带有 while 循环的函数使用多线程?

asp.net - 在ASP.NET中正确实现后台进程Thread

java - 无法从 ArrayList 生成随机顺序

java - 为什么在我停止 SAX 解析器后我的 InputStream 继续下载文件?

java - 不使用spark-submit.sh时,Spark如何知道Yarn资源管理器在哪里运行?