java - 为什么要用static修饰Lock对象

查看:234
本文介绍了java - 为什么要用static修饰Lock对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

package java_Thread;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

import java_Thread.AccountWithSyncUsingLock.Account;

public class ThreadCooperation {
    private static Account account = new Account();
    
    public static void main(String[] args){
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new DepositTask());
        executor.execute(new WithdrawTask());
        executor.shutdown();
        
        System.out.println("Thread 1\t\tThread 2\t\tBalance");
    }
    
    public static class DepositTask implements Runnable{
        public void run(){
            try{
                while(true){
                    account.deposit((int)(Math.random()*10+1));
                    Thread.sleep(1000);
                }
            }
            catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
    }
    
    public static class WithdrawTask implements Runnable{
        public void run(){
            while(true){
                account.withdraw((int)(Math.random()*10)+1);
            }
        }
    }
    
    private static class Account{
        private static Lock lock = new ReentrantLock();
        private static Condition newDeposit = lock.newCondition();
        private int balance = 0;
        
        public int getBalance(){
            return balance;
        }
        
        public void withdraw(int amount){
            lock.lock();
            try{
                while(balance < amount){
                    System.out.println("\t\t\tWait for a deposit");
                    newDeposit.await();
                }
                balance -=amount;
                System.out.println("\t\t\tWithdraw "+ amount+"\t\t" + getBalance());
            }
            catch(InterruptedException ex){
                ex.printStackTrace();
            }
            finally{
                lock.unlock();
            }
        }
        
        public void deposit(int amount){
            lock.lock();
            try{
                balance += amount;
                System.out.println("Deposit "+ amount + "\t\t\t\t\t" + getBalance());
                
                newDeposit.signalAll();
            }
            finally{
                lock.unlock();
            }
        }
    }
}

最近在学习JAVA的多线程,这是书上的例子。为什么声明Lock时要用static?这个例子中只创建了一个Account实例,但假如有多个Account实例的话,按道理它们之间应该是互不干扰的,但是Lock对象声明为类变量的话是不是逻辑就不对了?

解决方案

从整体的代码来说这里的static是多余的,因为ThreadCooperation中的Account对象是static的,而且Account中的balance是非static的,所以如果想要达成代码中的效果,其实Lock和Condition前面的static反而会造成误导。

这篇关于java - 为什么要用static修饰Lock对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆