[英]non-synchronized method can access by other thread,,,,,,,
The lock on an object by one thread, no other thread can enter any of the synchronized methods in that class ,but i want to know about non-synchronized method can access by other thread,,,,,,, 一个线程对一个对象的锁定,没有其他线程可以输入该类中的任何同步方法,但是我想知道非同步方法可以被其他线程访问,
class Account {
private int balance = 50;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
balance = balance - amount;
}
}
public class AccountDanger implements Runnable {
private Account acct = new Account();
public void run() {
for (int x = 0; x < 5; x++) {
this. d();
makeWithdrawal(10);
if (acct.getBalance() < 0) {
System.out.println("account is overdrawn!");
}
}
}
private synchronized void makeWithdrawal(int amt) {
if (acct.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName()
+ " is going to withdraw"+amt);
try {
Thread.sleep(500);
// Thread.sleep(500);
} catch (InterruptedException ex) {
}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()
+ " completes the withdrawal"+acct.getBalance());
} else {
System.out.println("Not enough in account for " + Thread.currentThread().getName()
+ " to withdraw " + acct.getBalance());
}
}
public static void main(String[] args) {
AccountDanger r = new AccountDanger();
Thread one = new Thread(r);
Thread two = new Thread(r);
one.setName("Fred");
two.setName("Lucy");
one.start();
two.start();
}
private void d() {
System.out.println("hhhhhhhhhhhhhhhhhhhhh"+Thread.currentThread().getName());
}
}
You have answer in your question itself :). 您在问题本身中有答案:)。 If you are just looking for confirmation : YES. 如果您只是在寻找确认信息:是。
No lock is required to access non-synchronized methods of an object. 不需要锁即可访问对象的非同步方法。
If you want to know more about these concepts, visit Object Locks 如果您想进一步了解这些概念,请访问对象锁
Yes, the unsynchronized methods can be accessed/called by any Thread, that has/gets the reference to the same instance. 是的,任何具有/获取对同一实例的引用的线程都可以访问/调用非同步方法。 Since you created a private Account instance and you didn't give this instance to any other class, in your example no other thread is able to access this special instance. 由于您创建了一个私人Account实例,并且没有将此实例分配给任何其他类,因此在您的示例中,其他线程都无法访问此特殊实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.