相當複雜的代碼,但這是一個非常簡單的問題。鎖定訪問另一個類,從運行方法
我有一個線程,這是它的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