package cn.haha.test;
//同步函数用到的同步监听器是隐式的,是this--因此,要想保持同步监听器是唯一的,只能在实现Runnable接口这样线程方式上使用同步函数
class Client implements Runnable{
private static int money=2000;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
getMoney();
}
}
//同步函数:一般情况下只能用实现Runnable这个方式
public synchronized void getMoney(){
money-=100;
if(money>0){
System.out.println(Thread.currentThread().getName()+"取了100元,还剩下"+money+"元");
}else{
System.out.println("钱已经取完了");
Thread.currentThread().stop();
}
}
}
public class Demo1 {
public static void main(String[] args) {
Client c=new Client();
Thread t1=new Thread(c,"老公");
Thread t2=new Thread(c,"老婆");
t1.start();
t2.start();
}
}
//同步函数用到的同步监听器是隐式的,是this--因此,要想保持同步监听器是唯一的,只能在实现Runnable接口这样线程方式上使用同步函数
class Client implements Runnable{
private static int money=2000;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
getMoney();
}
}
//同步函数:一般情况下只能用实现Runnable这个方式
public synchronized void getMoney(){
money-=100;
if(money>0){
System.out.println(Thread.currentThread().getName()+"取了100元,还剩下"+money+"元");
}else{
System.out.println("钱已经取完了");
Thread.currentThread().stop();
}
}
}
public class Demo1 {
public static void main(String[] args) {
Client c=new Client();
Thread t1=new Thread(c,"老公");
Thread t2=new Thread(c,"老婆");
t1.start();
t2.start();
}
}