同步使用

时间:2013-11-08 15:48:10

标签: java multithreading synchronization

  • 我编写了一个程序来打印n o t i f y,所有字母都用标签分隔。

  • 我使用了线程间通信,其中一个线程使用wait()notify()打印一个字母后跟另一个线程打印另一个线程。

  • 我得到n o t作为输出。那么i f y呢?为什么不打印?

代码:

package multi_threading; 

 public class test_value implements Runnable{
    static String name="notify";
    Thread t;
    static int len;
    boolean val=false;
    static int i;
    public test_value(){}
    public test_value(test_value obj,String msg){
        t=new Thread(obj,msg);
        t.start();
    }
    public static void main(String args[]){
        len=name.length();
        test_value obj=new test_value();
        new test_value(obj,"Child1"); 
        new test_value(obj,"Child2");
    }
    public void run(){
        synchronized(this){
          while(i<len){
          System.out.println("I got "+name.charAt(i));
          i++;
          val=!val;
          while(val){
              try{
                   wait();
                }catch(InterruptedException e){
                    System.out.println("Interrupted");
               }
           }
          notify();
        }
      }   
    }
 }

3 个答案:

答案 0 :(得分:0)

你不仅得到'n','o'和't',而且你的程序也没有结束......:)

您需要将while(val)更改为if (val)

一切顺利,(和调试是你的朋友)。此外,班级名称应为“大写骆驼案”。您的课程应该被称为TestValue,而不是test_value

答案 1 :(得分:0)

更好的是,你根本不需要val。

synchronized(this){
    while(i<len){
        System.out.println("I got "+name.charAt(i) + ", " + Thread.currentThread().getName());
        i++;    
        try{
            notify();
            wait();
        }catch(InterruptedException e){
            System.out.println("Interrupted");
        }
    }
}   

跑吧,得到输出:

I got n, Child2
I got o, Child1
I got t, Child2
I got i, Child1
I got f, Child2
I got y, Child1

通过使用接受的答案代码,我得到了输出:

I got n, Child1
I got o, Child2
I got t, Child2
I got i, Child1
I got f, Child1
I got y, Child2

这个并不像你想要的那样真正交替使用线程。 这源于notify实际上没有锁定的事实。它只是意味着当你放弃锁定时(当你等待时),你会让其中一个等待的线程知道它们轮到它了。

答案 2 :(得分:-1)

你的变量

boolean val=false;

不是静态的,所以每个线程都有自己的值,使其静态

static boolean val=false;