我知道
当您同步一段代码时,您指定要使用哪个对象的锁作为锁,例如,您可以使用一些第三方对象作为这段代码的锁。这使您能够在单个对象中拥有多个用于代码同步的锁。
但是,我不明白需要将参数传递给块。因为我是否将字符串的实例传递给同步块并不重要,因为同步块可以完美地工作,而与传递给块的参数无关。
所以我的问题是,无论如何,同步块是否会阻止两个线程同时进入临界区。那么为什么需要传递参数。(我的意思是默认获取某个随机对象的锁定)。
我希望我正确地提出了我的问题。
我已经尝试了以下示例,其中随机参数是同步块。
public class Launcher {
public static void main(String[] args) {
AccountOperations accOps=new AccountOperations();
Thread lucy=new Thread(accOps,"Lucy");
Thread sam=new Thread(accOps,"Sam");
lucy.start();
sam.start();
}
}
使用非静态同步块:
public class AccountOperations implements Runnable{
private Account account = new Account();
public void run(){
for(int i=0;i<5;i++){
makeWithdrawal(10);
}
}
public void makeWithdrawal(int amount){
String str="asd"
synchronized (str /* pass any non-null object the synchronized block works*/) {
if(account.getAmount()>10){
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
account.withdraw(amount);
System.out.println(Thread.currentThread().getName()+" has withdrawn 10, current balance "+ account.getAmount());
}else{
System.out.println("Insufficient funds "+account.getAmount());
}
}
}
}
使用静态同步块:
public class AccountOperations implements Runnable{
private static Account account = new Account();
public void run(){
for(int i=0;i<5;i++){
makeWithdrawal(10);
}
}
public static void makeWithdrawal(int amount){
synchronized (String.class /* pass any class literal synchronized block works*/) {
if(account.getAmount()>10){
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
account.withdraw(amount);
System.out.println(Thread.currentThread().getName()+" has withdrawn 10, current balance "+ account.getAmount());
}else{
System.out.println("Insufficient funds "+account.getAmount());
}
}
}
}