免責聲明:此代碼是從synchronized blocks for static and non-static methods線程調用靜態和非靜態方法
複製我做了一些修改它。我想知道如何使線程調用同步的靜態和非靜態方法。我可以通過將非靜態方法封裝在同步的塊中來使其工作。有沒有其他方法?
public class StaticNonStaticSynch
{
public static void main(String[] args)
{
final StaticNonStaticTest staticNonStaticTest = new StaticNonStaticTest();
Runnable runnable1 = new Runnable()
{
@Override
public void run()
{
staticNonStaticTest.nonStaticMethod();
}
};
Runnable runnable2 = new Runnable()
{
@Override
public void run()
{
StaticNonStaticTest.staticMethod();
}
};
Thread thread1 = new Thread(runnable1, "First Thread");
Thread thread2 = new Thread(runnable2, "Second Thread");
thread1.start();
thread2.start();
}
}
class StaticNonStaticTest
{
void nonStaticMethod()
{
//synchronized (StaticNonStaticTest.class){
for(int i=0;i<50;i++)
{
System.out.println("Non - Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
// }
}
static synchronized void staticMethod()
{
for(int i=0;i<50;i++)
{
System.out.println("Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
}
}
謝謝布賴恩!!!!!! – user547453
@brian:如果我們鎖定MyClass的實例會怎麼樣?它是否仍然保證我們不會得到ConcurrentModificationException,因爲當前線程在printAll()中時,沒有其他線程能夠訪問put()中的同步塊,並且該映射是私有的? – Kode
@Kode是的,它將保證非併發訪問,但是在該類上同步的任何其他內容也會導致該部分代碼被阻止。儘可能縮小同步範圍以避免瓶頸。 – Brian