java中线程lock问题?
最近在学java线程,看的书的《core java》,就仿照里面写了个例子。
定义了一个接口:
public interface Bank {
//转账方法
public void transfer(int from,int to,double amount) throws InterruptedException;
//总钱数
public double getTotalBalance();
}
定义了一个实现类:
public class LockBank implements Bank{
private Lock lock;
private Condition sufficientFunds;
......//还有一些变量比如:银行账户等等
//转账方法
public void transfer(int from,int to,double amount) throws InterruptedException {
lock.lock();
try {
while (this.accounts[from] < amount) {
sufficientFunds.await();
}
this.accounts[from] -= amount;
System.out.println("从账户" + from + "转向账户" + to + ":" + amount);
this.accounts[to] += amount;
System.out.println("总共:" + this.getTotalBalance());
sufficientFunds.signalAll();
} finally{
lock.unlock();
}
}
//总钱数方法
public double getTotalBalance() {
lock.lock();
try {
double sum = 0;
for (int i = 0; i < this.accountNum; i++) {
sum += this.accounts[i];
}
return sum;
} finally{
lock.unlock();
}
}
}
//定义一个线程类其中的run方法如下:
//线程RUN方法
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i <10; i++) {
int to=(int)(this.bank.getAccountNum()*Math.random());
double amount=this.maxAmount*Math.random();
try {
bank.transfer(this.from, to, amount);
//Thread.sleep((int)(this.delay*Math.random()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Test入口
public static void main(String[] args) {
//SynchronizedBank bank = new SynchronizedBank(ACCOUNTNUM,INITIALBALANCE);
LockBank bank = new LockBank(ACCOUNTNUM,INITIALBALANCE);
for (int i = 0; i < ACCOUNTNUM; i++) {
TransferRunnable transferRunnable = new TransferRunnable(bank,i,INITIALBALANCE);
Thread thread = new Thread(transferRunnable);
thread.start();
}
}
结果报:
Exception in thread "Thread-3"
java.lang.NullPointerException at com.zju.bank.LockBank.transfer(LockBank.java:48)
at com.zju.bank.TransferRunnable.run(TransferRunnable.java:68)
at java.lang.Thread.run(Thread.java:619)
lock我在LockBank中定义了 怎么回报为空的错误那。
------解决方案--------------------那是lock没初始化?
------解决方案--------------------
引入包:
import java.util.concurrent.locks.*;
再把lock初始化:
lock=new ReentrantLock();
试试看。
------解决方案--------------------你的lock没有初始化啊肯定报
空指针了