public class SynMethon implements Runnable{
private double money=1000000;
public void run(){
dbMoney();
}
//同步方法
private synchronized void dbMoney(){
Thread t=Thread.currentThread();
for(int i=1;i<=10;i++){
if(t.getName().equals( "会计" )){
money+=i*10;
System.out.println( t.getName()+"正在整理账户" );
}
if(t.getName().equals( "出纳" )){
money-=i*5;
System.out.println( t.getName()+"正在支取账户" );
}
System.out.println( "当前金额为"+money );
try {
Thread.sleep( 1000 );
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
测试类public class test110 {
public static void main(String[] args){
//测试同步方法
SynMethon synMethon=new SynMethon();
Thread kuaiji=new Thread( synMethon,"会计" );
kuaiji.setPriority( Thread.MAX_PRIORITY );
kuaiji.start();
Thread chuna=new Thread( synMethon,"出纳" );
chuna.start();
}
}
运行结果