java 多线程 资源共享
在控制资源共享的语句外,加入 synchronized(this) (this也可用private Object o 对象),来进行写锁保护 ,例如
class M
{
private static M m = new M();
public static M getInstance()
{
return m;
}
public void check(int i)
{
System.out.println("I"m waiting, Thread "+i);
synchronized(this)
{
System.out.println("I"m processing, Thread "+i);
try {
Thread.sleep(5000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
synchronized void method(int i)
{
System.out.println("I"m in synchronized function "+ i);
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class CheckCloneable implements Runnable
{
private int i;
private boolean test_function_syn;
CheckCloneable(int i,boolean test_function_syn)
{
this.i = i;
this.test_function_syn = test_function_syn;
}
public void run()
{
M m = M.getInstance();
if(!test_function_syn)
{
m.check(i);
}
else
{
System.out.println("I"m waiting synchronized function "+ i);
m.method(i);
}
}
public static void main(String[] args)
{
for(int i=0;i<5;i++)
{
System.out.println("main");
CheckCloneable c = new CheckCloneable(i,true);
Thread t = new Thread(c);
t.start();
}
}
} |