我会使用“虚拟”对象并对其进行同步。块级别更有效,因为它不会锁定整个方法。
Object xLock = new Object(); // !!! in you main thread
....
public void writeToFile() {
synchronized(xLock ){
System.out.println("Thread accessed");
//Some stuff here
System.out.println("Thread FINISHED!");
}
}
但当然你也可以写:
public void writeToFile() {
synchronized(this){
System.out.println("Thread accessed");
//Some stuff here
System.out.println("Thread FINISHED!");
}
}
}
请记住,xLock
应该在主线程中启动。
作为参考
=======================
方法级别
class MethodLevel {
//shared among threads
SharedResource x, y ;
public void synchronized method1() {
//multiple threads can't access
}
public void synchronized method2() {
//multiple threads can't access
}
public void method3() {
//not synchronized
//multiple threads can access
}
}
块级
class BlockLevel {
//shared among threads
SharedResource x, y ;
//dummy objects for locking
Object xLock = new Object();
Object yLock = new Object();
public void method1() {
synchronized(xLock){
//access x here. thread safe
}
//do something here but don't use SharedResource x, y
// because will not be thread-safe
synchronized(xLock) {
synchronized(yLock) {
//access x,y here. thread safe
}
}
//do something here but don't use SharedResource x, y
//because will not be thread-safe
}//end of method1
}