Java 线程小知识

1、线程的状态有新建、就绪、运行、阻塞、死亡。
2、创建线程通过继承Thread类或实现Runable接口。
3、线程的start()方法作用是开启一个线程执行run方法,且start不允许重复调用,线程的run()方法,则是在当前主线程中调用线程的run方法,可以重复调用,如果直接调用run()方法,意味着会将run()当一个主方法进行执行,并不会在一个线程中进行执行。
4、Synchronized同步锁,给方法添加同步锁后,一次只允许一个线程进行访问,其他线程进入阻塞状态,等待前一个线程访问结束后方可访问。
5、notify()随机唤醒一个线程;notifyAll()唤醒所有的线程;wait()让当前线程处于阻塞状态,等待唤醒;wait(1000)等待1秒;join暂停当前线程等待调用的线程优先执行完成。
6、Semaphore进行限流,定义最大线程数量。

public class Acount {
    private int money;
    public Acount(int money) {
        this.money = money;
    }
    
    public synchronized void getMoney(int money){
        while (this.money < money || this.money == 0) {
            System.out.println("取款:"+money+",当前余额Semaphore为:"+this.money+",余额不足,请等待:");
            try {
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.money = this.money - money;
        System.out.println("取出:"+money+" 还剩余:"+this.money);
    }
    
    public synchronized void setMoney(int money) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            // TODO: handle exception
        }
        this.money = this.money + money;
        notifyAll();
        System.out.println("存入:"+money+" 还剩余:"+this.money);
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        Acount acount = new Acount(0);
        Blank blank = new Blank(acount);
        Customer customer = new Customer(acount);
        
        Thread thread1 = new Thread(blank);
        Thread thread2 = new Thread(customer);
        
        thread1.start();
        thread2.start();
    }

}

class Blank extends Thread{
    Acount acount;
    public Blank(Acount acount){
        this.acount = acount;
    }
    
    public void run(){
        while(true){
            int money = (int)(Math.random() * 1000);
            acount.setMoney(money);
        }
    }
}

class Customer extends Thread{
    Acount acount;
    public Customer(Acount acount){
        this.acount = acount;
    }
    
    public void run(){
        while(true) {
            int money = (int)(Math.random() * 1000);
            acount.getMoney(money);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值