import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTese {
public static void main(String[] args) {
Apple a = new Apple();
Thread t1 = new Thread(a,"001");
Thread t2 = new Thread(a,"002");
Thread t3 = new Thread(a,"003");
//t1.setName("");
t1.start();
t2.start();
t3.start();
}
}
class Apple implements Runnable{
private int apple = 50;
private String color ;
private String name ;
Lock lock = new ReentrantLock();
@Override
public void run() {
lock.lock();
while(apple>0){
if (apple%2==0) {
color = "黄色";
name = "黄香蕉";
}
System.out.println(Thread.currentThread().getName()+"="+name+"="+color+"--"+apple);
apple--;
lock.unlock();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.lock();
if(apple%2==1){
color = "红色";
name = "红香蕉";
}
lock.unlock();
}
}
}
Exception in thread "002" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:460)
001=黄香蕉=黄色--46
at 多线程练习.Apple.run(LockTese.java:35)
at java.lang.Thread.run(Thread.java:744)
Exception in thread "001" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:460)
003=红香蕉=红色--45
at 多线程练习.Apple.run(LockTese.java:35)
at java.lang.Thread.run(Thread.java:744)
Exception in thread "003" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:460)
at 多线程练习.Apple.run(LockTese.java:35)
at java.lang.Thread.run(Thread.java:744)
为什么lock.lock()锁放在while(){
lock.lock()
}边就不报错呢儿现在就报错呢? |
|