java实现线程安全的栈(链式储存)

package com.boco.stackTest.sxlTest;

import com.boco.stackTest.LinkStack;
import com.boco.stackTest.Stack;
import com.boco.stackTest.link.LinkNode;
import com.boco.stackTest.sxlTest.ConcurrentTest.ConcurrentTask;

public class Test {
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//使用自己实现的栈进行初始化
		final Stack s = new LinkStack();
		//创建多个线程同时压栈,64位JVM可以开到10000+,32位JVM可以开到2000~3000之间
		int threadNum = 2000;
		ConcurrentTask[] task = new ConcurrentTask[threadNum];
		long start = System.nanoTime();
		for (int i = 0; i < task.length; i++) {
			task[i] = new ConcurrentTask() {
				public void run() {
					LinkNode node = new LinkNode(1,"name");
					s.push(node);
				}
			};
		}
		new ConcurrentTest(task);
		long end = System.nanoTime();
		//打印所有线程的入栈时间
		System.out.println("total time: " + (end - start)/1.0e9);
		/*
		 * 测试时要保证下面打印的i和上面初始化的线程数threadNum一致,
		 * 因为如果是线程安全的栈,入栈和出栈的数目应该是一样的。
		 * 如果要单独测试上面的total time:时间,可以将下面的代码注释掉进行测试。
		 */
		System.out.println("pop ------------------------------------");
		for (int i=1;;i++) {
			LinkNode l = s.pop();
			if(l == null)
				break;
			System.out.println(i + "	"+l.getKey()+"                " + l.getValue());
		}
	}

}


 

 

 

package com.boco.stackTest.sxlTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
  ConcurrentTask[] task = new ConcurrentTask[5];
  for(int i=0;i list = new CopyOnWriteArrayList();
	private AtomicInteger err = new AtomicInteger();//原子递增
	private ConcurrentTask[] task = null;
	
	public ConcurrentTest(ConcurrentTask... task){
		this.task = task;
		if(task == null){
			System.out.println("task can not null");
			System.exit(1);
		}
		doneSignal = new CountDownLatch(task.length);
		start();
	}
	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 */
	private void start(){
		//创建线程,并将所有线程等待在阀门处
		createThread();
		//打开阀门
		startSignal.countDown();//递减锁存器的计数,如果计数到达零,则释放所有等待的线程
		try {
			doneSignal.await();//等待所有线程都执行完毕
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//计算执行时间
		getExeTime();
	}
	/**
	 * 初始化所有线程,并在阀门处等待
	 */
	private void createThread() {
		long len = doneSignal.getCount();
		for (int i = 0; i < len; i++) {
			final int j = i;
			new Thread(new Runnable(){
				public void run() {
					try {
						startSignal.await();//使当前线程在锁存器倒计数至零之前一直等待
						long start = System.nanoTime();
						task[j].run();
						long end = System.nanoTime();
						double time = (end - start) / 1.0e6;
						list.add(time);
					} catch (Exception e) {
						err.getAndIncrement();//相当于err++
					} 
					doneSignal.countDown();
				}
			}).start();
		}
	}
	/**
	 * 计算平均响应时间
	 */
	private void getExeTime() {
		int size = list.size();
		List _list = new ArrayList(size);
		_list.addAll(list);
		Collections.sort(_list);
		double min = _list.get(0);
		double max = _list.get(size-1);
		double sum = 0L;
		for (Double t : _list) {
			sum += t;
		}
		double avg = sum/size;
		System.out.println("min: " + min);
		System.out.println("max: " + max);
		System.out.println("avg: " + avg);
		System.out.println("err: " + err.get());
	}
	
	public interface ConcurrentTask {
		void run();
	}

}


 

 

package com.boco.stackTest;

import java.util.Map;

import com.boco.stackTest.link.LinkNode;

/**
 * 实现线程安全的栈
 * @author Administrator
 *
 */
public class LinkStack implements Stack {
	
	/**
	 * 栈顶指针
	 */
	public LinkNode top = null;
	
	private int length=0;
	
	public LinkStack(){
        top = new LinkNode(0, "null");
    } 
	
	public LinkNode pop() {
		synchronized(this){
			top = top.getNext();
			length--;
			return top;
		}
	}

	public void push(LinkNode element) {
		synchronized(this){
			if(element != null){
				element.setNext(top);
             	top = element;
        		length++;
			}
		}
	}
	
    /**
     * 打印栈内元素
     * @param currentNode
     */
    public void printStack(){
    	LinkNode currentNode = top;
        if(currentNode != null){
        	System.out.println("===========================================================");
            while(currentNode != null){
                System.out.println("key="+currentNode.getKey()+"--name="+currentNode.getValue());
                currentNode = currentNode.getNext();
            }
        	System.out.println("===========================================================");
        }
        else{
            System.out.println("the stack is null");
        }
    }
    
    public int length(){
    	return length;
    }

}


 

 

 

package com.boco.stackTest;

import com.boco.stackTest.link.LinkNode;

public interface Stack {
	/**
	 * 将元素压入栈中
	 * @param string
	 */
	public void push(LinkNode string);
	/**
	 * 弹出栈顶元素
	 */
	public LinkNode pop();
	/**
	 * 打印当前栈中所有元素
	 */
	public void printStack();
	/**
	 * 返回当前栈中元素个数
	 * @return
	 */
	public int length();
}


 

 

 

package com.boco.stackTest.link;

public class LinkNode {
	 private int key = 0;
     private String value = null;
     private LinkNode next = null;
    
     public LinkNode(int key, String data){
         this.key = key;
         this.value = data;
         this.next = null;
     }
    
     public int getKey() {
         return key;
     }

     public void setKey(int key) {
         this.key = key;
     }


     public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public LinkNode getNext() {
         return next;
     }

     public void setNext(LinkNode next) {
         this.next = next;
     }
}


 

你可能感兴趣的:(技术学习)