package com.bjsxt.d822.a2;
public class SubThread9 extends Thread {
/*
* 当多个对象同时对同一个资源操作,则必须使用同步机制来控制。
*
* 1、当方法去操作共享资源时,则该方法必须通过 synchronized关键字来修饰。
* 2、当方法被 synchronized 关键字修饰时,还需要 wait() 和 notify()两个方法配合使用。
* wait()方法是让当前线程对象进入等待状态。
* notify()方法是让当前线程对象对唤醒等待者。
*/
private int sum = 0;
@Override
public synchronized void run() {
String name = this.getName();
System.out.println( name + "统计员,开始统计了.......");
for(int i = 1; i <= 100; i++ ){
sum += i;
try {
Thread.sleep( 100 );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + "统计员,已将1至100的累加结果统计完毕。");
this.notify(); //唤醒等待者。
}
//获取sum的值。
//public int getSum() {
public synchronized int getSum() { //犯过的错误:没有写synchronized来修饰getSum()方法,以至于出现了java.lang.IllegalMonitorStateException 异常
try {
System.out.println( Thread.currentThread().getName() + " 经理在这儿等待结果........");
this.wait(); //等待
} catch (InterruptedException e) {
}
return sum;
}
}
package com.bjsxt.d822.a2;
public class SubThread9Test {
public static void main(String[] args) {
System.out.println( Thread.currentThread().getName() + " 经理,开始工作了...... ");
SubThread9 st = new SubThread9();
st.setName("张三");
st.start();
System.out.println( st.getName() + " 统计员,你能把1 + 2 + 3 + ... + 100 的结果给我的吗?");
System.out.println("没问题,但您需要等一会儿。");
// try {
// Thread.sleep( 15000 );
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("统计结果是: " + st.getSum() );
}
}
因为在SubThread9类中getSum()没有用synchronized 修饰,直接写成 public int getSum(){} 而导致了异常java.lang.IllegalMonitorStateException的出现 |