67,513
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
Account account=new Account(100);
Person p1=new Person(account,80);
Person p2=new Person(account,90);
p1.start();
p2.start();
}
}
class Account{
int total;
public Account(int total) {
super();
this.total=total;
}
}
class Person extends Thread{
private int reduce;
public Account account;
public Person(Account account,int reduce) {
this.account=account;
this.reduce=reduce;
}
public synchronized void run() {
if (account.total-reduce<0) return ;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
account.total-=reduce;
System.out.println(Thread.currentThread().getName()+"取出"+reduce);
System.out.println(Thread.currentThread().getName()+"剩余"+account.total);
}
}
public synchronized void run() {...}
等价于public void run(
synchronized (this){...}
)
public class Test {
public static void main(String[] args) {
Account account=new Account(100);
Person p1=new Person(account,80);
Person p2=new Person(account,90);
p1.start();
p2.start();
}
}
class Account{
int total;
public Account(int total) {
super();
this.total=total;
}
}
class Person extends Thread{
// Abel: 加一个类锁。这种方法很低效,应该把锁加到账户上。这里只是为了指出代码问题。
private static Object lock = new Object();
private int reduce;
public Account account;
public Person(Account account,int reduce) {
this.account=account;
this.reduce=reduce;
}
// Abel: 改为使用类静态对象lock加锁
public void run() {
synchronized(lock) {
if (account.total-reduce<0) return ;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
account.total-=reduce;
System.out.println(Thread.currentThread().getName()+"取出"+reduce);
System.out.println(Thread.currentThread().getName()+"剩余"+account.total);
}
}
}