本帖最后由 官仁杰 于 2012-10-19 12:41 编辑
相当于复写毕老师视频的代码,写出来结果不正确- public class InOutDemo {
- public static void main(String[] args) {
- Person p = new Person();
- new Thread(new DataIn(p)).start();
- new Thread(new DataOut(p)).start();
- }
- }
- class Person{
- String name;
- int age;
- boolean flag = true;
- }
- class DataIn implements Runnable{
- private Person p;
- DataIn(Person p){
- this.p = p;
- }
- @Override
- public void run() {
- int x = 0;
- while(true){
- synchronized(p){
- if(!p.flag){
- try {
- p.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- if(x == 0){
- p.name = "Linda";
- p.age = 10;
- }
- else{
- p.name = "Peter";
- p.age =20;
- }
- x = x == 0? 1:0;
- p.flag = false;
- p.notify();
- }
- }
- }
- }
- class DataOut implements Runnable{
- private Person p;
- DataOut(Person p){
- this.p = p;
- }
- @Override
- public void run() {
- while(true){
- synchronized(p){
- if(p.flag){
- try {
- p.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(p.name +"的年龄是" +p.age);
- }
- p.flag = true;
- p.notify();
- }
- }
- }
复制代码 输出Exception in thread "Thread-1" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method)
at DataOut.run(InOutDemo.java:69)
at java.lang.Thread.run(Unknown Source)
Linda的年龄是10
|