import java.util.concurrent.locks.*;
class ThreadTest7_1
{
public static void main(String[] args)
{
Bank_1 b=new Bank_1();
Person p=new Person(b);
Thread t1=new Thread(p,"用户A");
Thread t2=new Thread(p,"用户B");
t1.start();
t2.start();
}
}
class Bank_1
{
Lock lock=new ReentrantLock();
int num=0;
public void CM(int x)
{
lock.lock();
for(int y=0;y<3;y++)
{
num=num+x;
System.out.println(Thread.currentThread().getName()+":"+num);
lock.unlock();
}
}
}
class Person implements Runnable
{
private Bank_1 b;
Person(Bank_1 b)
{
this.b=b;
}
public void run()
{
b.CM(100);
}
}
然后运行的时候就弹出了
用户A:100
用户A:200
用户B:300Exception in thread "用户A"
用户B:400
Exception in thread "用户B" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Sour
ce)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown
Source)
at java.util.concurrent.locks.ReentrantLock.unlock(Unknown Source)
at Bank_1.CM(ThreadTest7_1.java:26)
at Person.run(ThreadTest7_1.java:39)
at java.lang.Thread.run(Unknown Source)
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Sour
ce)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown
Source)
at java.util.concurrent.locks.ReentrantLock.unlock(Unknown Source)
at Bank_1.CM(ThreadTest7_1.java:26)
at Person.run(ThreadTest7_1.java:39)
at java.lang.Thread.run(Unknown Source)
|
|