synchronized 关键字的使用
三种使用方法
1.定义在普通方法上 ,锁的是操作这个方法的对象 ,即this;
2.定义在同步代码块,同步代码块锁的是()内的对象;
3.定义在静态方法上,锁的是类的模板对象:class对象,同一个类的对象都是获得同一把锁。
package com.jacob.thread.sxtsynchronized;
public class TestSyn {
public static void main(String []args) {
Money m = new Money(100);
new BankATM(m).start();
new BankATM(m).start();
}
}
class Money{
int num;
Money(int num){
this.num=num;
}
}
class BankATM extends Thread{
static Money money;
BankATM(Money money)
{
this.money=money;
}
public void run() {
func();
}
static synchronized void staticfunc() {
while(money.num>0)
{money.num--;
System.out.println(Thread.currentThread().getName()+"现在还剩:"+money.num);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void func() {
while(money.num>0)
{money.num--;
System.out.println(Thread.currentThread().getName()+"现在还剩:"+money.num);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void kuai() {
synchronized(money){
while(money.num>0)
{money.num--;
System.out.println(Thread.currentThread().getName()+"现在还剩:"+money.num);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
}
}