Java中条件变量使用示例及性能测试

来源:互联网 发布:ubuntu mate 输入法 编辑:程序博客网 时间:2024/05/01 09:10
   和前篇文章一样的目的,测试结果也差不多,不过java中的条件变量效率略高于boost,结果是每秒大概20w出头。

===================================================================================
package com.cc;

public class Test {
   
    staticboolean running_flag = true;
    staticObject obj = new Object();
    static intcnt = 0;
    staticboolean ball = true;
   
    privatestatic class Run1 implements Runnable {
          public Run1(){}
       
          public voidrun() {
             int i =0;
            while(running_flag){
               synchronized(obj)
                {
                   while (ball!= true && running_flag){
                      try {
                        obj.wait();
                      } catch(InterruptedException e) {
                        e.printStackTrace();
                             
                   }
                   ++i;
                   ++cnt;
                   if(running_flag){
                      ball =false;
                     obj.notifyAll();                  
                   }
                             
              
            synchronized(obj)
             {
               System.out.println(i);               
                   
          }
    }

    private static class Run2 implements Runnable{
          public Run2(){}
         
          public voidrun() {
             int i =0;
            while(running_flag){
               synchronized(obj)
                {
                   while (ball!= false && running_flag){
                      try {
                        obj.wait();
                      } catch(InterruptedException e) {
                        e.printStackTrace();
                             
                   }
                   ++i;
                   ++cnt;
                   if(running_flag){
                      ball =true;
                     obj.notifyAll();                  
                   }
                             
              
            synchronized(obj)
             {
               System.out.println(i);               
                   
          }
    }
   
    publicstatic void main(String[] args) throws InterruptedException {
       Threadthread1 = new Thread(new Run1());
       Threadthread2 = new Thread(new Run2());
      thread1.start();
      thread2.start();
      Thread.sleep(1000);
       running_flag= false;
      synchronized(obj)
       {
         obj.notifyAll();
       }
      thread1.join();   
      thread2.join();
      System.out.println(cnt);
    }

}
========================================================================
0 0
原创粉丝点击