多线程编程 java.lang.IllegalMonitorStateException at java.lang.Object.wait

anlian523 2017-06-22 10:59:16
写两个线程,其中一个线程打印1-52,另一个打印A-Z,打印顺序为12A34B56C....5152Z。没有用同步方法或者同步代码块。用的lock和condition,还用了下线程池。不知道为什么报异常,它意思我在wait的时候没有获得锁,但实际要进入wait前肯定是获得锁了的呀,困惑中,代码如下求解答。
package testSix;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Print
{
private boolean flag = false;
public int num = 1;
public char chr = 'A';

private final Lock lock=new ReentrantLock();
private final Condition cond=lock.newCondition();

public void printNumber()
{
lock.lock();
try
{
if(flag)
{
if(num <= 52)
{
cond.wait();
}
}
else
{
//进入else进入了26次
System.out.print(num);
System.out.print(num + 1);
num += 2;
flag = true;
cond.signalAll();
}
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
finally
{
lock.unlock();
}
}

public void printWord()
{
lock.lock();
try
{
if(!flag)
{
if(chr <= 'Z')
{
cond.await();
}
}
else
{
System.out.print(chr);
chr += 1;
flag = false;
cond.signalAll();
}
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
finally
{
lock.unlock();
}
}
}


package testSix;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;



public class printTest {

public static void main(String[] args) {
// TODO Auto-generated method stub

Print p = new Print();
ExecutorService service = Executors.newCachedThreadPool();
service.execute(()->{
for(int i = 0; i < 52; i ++)
{
p.printNumber();
}

});
service.execute(()->{
for(int i = 0; i < 52; i ++)
{
p.printWord();
}

});


}

}

...全文
412 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
anlian523 2017-06-22
  • 打赏
  • 举报
回复
引用 2 楼 soton_dolphin 的回复:
少了个a 啊,应该是if(num <= 52) { cond.await(); }
对哈,怪我不仔细了。改了就对了,运行结果对了,但是看见console那个红色正方形先亮了一会,然后就没了。说明是finally最终把锁释放了,所以最后没有阻塞吗?还有就是以下这段代码应该已经设置阻塞的终点,应该打印完就不会阻塞了啊? if(flag) { if(num <= 51) { cond.await(); } }
soton_dolphin 2017-06-22
  • 打赏
  • 举报
回复
少了个a 啊,应该是if(num <= 52) { cond.await(); }
anlian523 2017-06-22
  • 打赏
  • 举报
回复
12AException in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Unknown Source) at testSix.Print.printNumber(Print.java:25) at testSix.printTest.lambda$1(printTest.java:28) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 实际上是先打印出来12A后,才开始报异常的
soton_dolphin 2017-06-22
  • 打赏
  • 举报
回复
那个红色正方形是“停止“钮””程序运行时会变红色,程序运行完就变灰红色

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧