...
lock.lock()
try{
...
}
finally{
lock.unlock()}
...
我注意到这并不能确保绝对互斥,而同步总是如此,那么两者之间到底有什么区别?
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Guys extends Thread{
public static void go()throws InterruptedException{
final Lock lock = new ReentrantLock();
lock.lock();
try{
System.out.println("global " + main.global);
main.global = main.global + 100;
}
finally
{
lock.unlock();
}
}
public void run(){
try{
for(int i = 0; i <1; i++)
{
System.out.println(this);
go();
}
} catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
}
}
我的线程共享一个资源。在这种情况下,只有同步有效。