相当复杂的代码,但这是一个非常简单的问题。锁定访问另一个类,从运行方法
我有一个线程,这是它的run方法:
public void run() //gets pages and writes to them
{ // i printed the pageId of every process to check they are running at the same time and competing for resources
for(ProcessCycle currentCycle : processCycles.getProcessCycles())
{
Long[] longArray = new Long[currentCycle.getPages().size()];
try {
Page<byte[]>[] newPages = mmu.getPages(currentCycle.getPages().toArray(longArray));
for(int i = 0; i < newPages.length; i++)
{
MMULogger.getInstance().write("GP:P" + id + " " + currentCycle.getPages().get(i) + " " + Arrays.toString(currentCycle.getData().get(i)), Level.INFO);
}
List<byte[]> currentPageData = currentCycle.getData();
System.out.println("process id " + id);
for(int i = 0; i < newPages.length;i++)
{
byte[] currentData = currentPageData.get(i);
newPages[i].setContent(currentData);
}
Thread.sleep(currentCycle.getSleepMs());
} catch (ClassNotFoundException | IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
不打扰阅读它的全部。只需注意在mmu.getpages之后有一个for循环。
虽然进程在for循环中,但我想锁定对所有其他线程的访问权限。 synchronized是不好的,因为我的原始过程不再是mmu,而是在for循环中,并且reentrantlock可能是个好主意,但我对语法不熟悉并遇到了一些问题。
长话短说 - 我如何让所有其他线程等待,而某些线程在mmu.getpages之后的for循环内?
你有三个for循环,你是指哪一个?第一个for'newPages'循环? – hotzst
是的。第一个,通过newPages,在mmu.getpages下面 –
该代码在设计上有些破碎。这是违反直觉的,并且容易出错将某些东西锁定在getter(例如,如果在调用getPages(...)后没有解锁锁定/信号/无论什么人都不能调用getPages (......)再次)。你能否详细说明你想做什么?这似乎是[XY-Problem](http://meta.stackexchange.com/a/66378)。 – Turing85