我有两节课,一节课和二节课。首先在类中,我只运行两个线程。类Second有两个方法,一个用于更改静态变量数组,另一个用于更改后读取数组。我想通过等待和通知来做这件事。
class First{
public static void main(String[] args){
Second s1 = new Second(1);
Second s2 = new Second(2);
s1.start();
s2.start();
}
}
class Second extends Thread{
private static int[] array = {1, 2, 3};
private int number;
Second(int number){
this.number = number;
}
public void run(){
change();
System.out.println("Out of change: " + getName());
read();
}
public synchronized void change(){
if(array[0] != 1)
return;
System.out.println("Change: " + getName());
for(int i = 0; i < 10; i++)
array[0] += i;
notify();
}
public synchronized void read(){
try{
System.out.println("Waiting for change:" + getName());
wait();
}
catch(InterruptedException ie){
ie.printStackTrace();
}
System.out.println("Score: " + array[0]);
}
}我去叫IllegalMonitorException。我想让一个线程将数组改为46,然后在两个线程中读取数组。如何解决这个问题?我必须使用锁变量吗?
发布于 2013-08-25 07:58:21
为了使用wait,您必须从同步方法中调用它。您正在从非同步方法调用它。同步read可以解决这个问题。
顺便说一句,锁定数组而不是线程会更好,因为这是需要对数据进行控制的地方。你可以让你的方法不同步,然后把所有的代码放在里面:
synchronized(array) {
// put all the code here
}然后将对wait和notify的调用更改为array.wait和array.notify。
https://stackoverflow.com/questions/18424339
复制相似问题