⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 synch.java

📁 java 数据结构的一些简单实例和一些线程的应用主要是面向初学者
💻 JAVA
字号:
import java.util.*;
import java.text.*;
public class Synch {
	private static long[] locking_time =new long[100];
	private static long[] not_locking_time=new long[100];
	private static final int ITERATION=100000;
	synchronized long locking(long a,long b){return a+b;}
	long not_locking(long a,long b){return a+b;}
    
	private void test(int id){
    	long start=System.currentTimeMillis();
    	
    	for(long i=ITERATION;--i>=0;)
    	{
    		locking(i,i);
    	}
    	locking_time[id]=System.currentTimeMillis()-start;
    	start =System.currentTimeMillis();
    	
    	for(long i=ITERATION;--i>=0;){
    		not_locking(i,i);
    	}
    	not_locking_time[id]=System.currentTimeMillis()-start;
    }
    static void print_result(int id){
    	NumberFormat compositor=NumberFormat.getInstance();
    	compositor.setMaximumFractionDigits(2);
    	double time_in_Synchronization=locking_time[id]-not_locking_time[id];
    	
    	System.out.println("pass"+id+": Time lost:"+compositor.format(time_in_Synchronization)+"ms."
    			+compositor.format(((double)locking_time[id]/not_locking_time[id])*100)
    			+"% increase");
    }
    static public void main(String[] args)throws InterruptedException{
    	final Synch tester=new Synch();
    	tester.test(0);print_result(0);
    	tester.test(1);print_result(1);
    	tester.test(2);print_result(2);
    	tester.test(3);print_result(3);
    	tester.test(4);print_result(4);
    	tester.test(5);print_result(5);
    	tester.test(6);print_result(6);
    	tester.test(7);print_result(7);
    	tester.test(8);print_result(8);
    	
    	final Object start_gate=new Object();
    	
    	Thread t1=new Thread()
    	{
    		public void run(){
    			try{
    				synchronized(start_gate){start_gate.wait();}
    			   }catch(InterruptedException e){}
    			
    			tester.test(9);
    			
    		}
    	};
    	
       Thread t2=new Thread()
       {
    	  public void run()
    	  {
    		  try{
    			  synchronized(start_gate){start_gate.wait();}
    		  }catch(InterruptedException e){}
    		  tester.test(8);
    	  }
      };
      Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
      t1.start();
      t2.start();
      synchronized(start_gate){start_gate.notifyAll();}
      t1.join();
      t2.join();
      
      print_result(8);
      print_result(9);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -