Java并发容器

博客介绍了Java同步容器BlockingQueue的不同操作特点,如put和Take会阻塞、Add和Remove抛出异常等。还提及实现简单解析web,以及StampedLock读锁不阻塞写锁。同时阐述了Java内存模型中volatile变量读写时共享变量的处理机制。

同步容器:

       //Vector  ArrayList  CopyOnWriteArrayList
	ArrayList<String> s=new ArrayList<>();
	Collections.synchronizedList(s);
	
	//Hashtable  HashMap  ConcurrentHashMap
	HashMap<String, Object> resHashMap=new HashMap<>();
	Collections.synchronizedMap(resHashMap);
	}

  BlockingQueue:

put和Take 阻塞的

Add和Remove抛出异常

Offer和poll  有返回值得

public class Demo33 {
   public static void main(String[] args) {
	   
	  ThreadPoolExecutor threadPool=
			  new ThreadPoolExecutor(10,20,10,TimeUnit.DAYS,
					  new ArrayBlockingQueue<>(10),
					  new DiscardOldestPolicy());
	  AtomicInteger count=new AtomicInteger();
	  for(int i=0;i<100;i++){
		  threadPool.execute(new Runnable() {
			
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
			    count.getAndIncrement();
			}
		});
	  }
	  threadPool.shutdown();
	  while(Thread.activeCount()>1){
		  
	  }
	  System.out.println(count.get());
   }
}

  

public class Demo44 {
	public static void main(String[] args) {
		//10.个线程来处理大量的任务
		//ThreadPoolExecutor pool=new ThreadPoolExecutor(10,10,0,TimeUnit.MILLISECONDS,
				//new LinkedBlockingQueue<>());
		ExecutorService pool=Executors.newFixedThreadPool(10);
		ExecutorService pool1=Executors.newCachedThreadPool();
		ExecutorService pool2=Executors.newSingleThreadExecutor();
		ExecutorService pool3=Executors.newScheduledThreadPool(10);
		
		ThreadFactory tf=new ThreadFactory() {
			
			@Override
			public Thread newThread(Runnable r) {
				Thread thread=newThread(r);
				return null;
			}
		};
		while(true){
			pool.execute(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			});
		}
	}

}

  实现简单的解析web:

public class HttpService2 {
public static void main(String[] args) throws Exception{
	ExecutorService pool=Executors.newCachedThreadPool();
	
	ServerSocket server=new ServerSocket(8888);
	System.out.println("服务器启动,监听"+8888+"端口");
	
	while(!Thread.interrupted()){
		Socket client=server.accept();
		pool.execute(new ServerThread(client));
		//new Thread(new ServerThread(client)).start();
	}
}
}

  

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class ServerThread implements Runnable{
	private static Map<String, String> contentMap=new HashMap<>();
	static{
		contentMap.put("html", "text/html;charset=utf-8");
		contentMap.put("jpg", "image/jpeg");
	}
	private Socket client;
	private InputStream ins;
	private OutputStream out;
	private PrintWriter pw;
	private BufferedReader br;
	
	public ServerThread(Socket client) {
		this.client=client;
		init();
	}
	private void init() {
		 try {
			ins=client.getInputStream();
			out=client.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run(){
		try {
			go();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	private static final String webroot="";
	
	public void go() throws Exception{
		//读取请求信息
		  BufferedReader reader=new BufferedReader(new InputStreamReader(ins));
		   String line=reader.readLine().split(" ")[1].replace("/", "\\");
		   System.out.println(line);
		   if(line.equals("\\")){
			   line +="index.html";
		   }
		   
		   //给用户响应
		   PrintWriter pw=new PrintWriter(out);
		   
		   InputStream i=new FileInputStream(webroot+line);
		   //BufferedReader fr=new BufferedReader(new InputStreamReader(i));
	       pw.println("HTTP/1.1 200 OK");
	       pw.print("Content-Type:"+
	       contentMap.get(line.substring(
	    		   line.lastIndexOf(".")+1,line.length())));
	       pw.println("Content-Length:"+i.available());
	       pw.flush();
	       String c=null;
	       byte[] buff=new byte[1024];
	       int len=0;
	       while((len=i.read(buff))!=-1){
	    	   out.write(buff,0,len);
	       }
//	       while((c=fr.readLine())!=null){
//	    	   pw.print(c);
//	       }
	       pw.flush();
	       //i.close();
	       //fr.close();
	       pw.close();
	       reader.close();
	       client.close();       
	}
}

  StampedLock:读锁并不会阻塞写锁

import java.util.concurrent.locks.StampedLock;

public class Demo55 {
   private int balance;
   private StampedLock lock=new StampedLock();
   public void conditionReadWrite(int value){
	   //判断balance是否符合跟新的条件
	   long stamp=lock.readLock();
	   while (balance>0) {
		  //转换成写锁
		   long writeStamp=lock.tryConvertToWriteLock(stamp);
		   if(writeStamp!=0){  //成功转换成写锁
			   stamp=writeStamp;
			   balance+=value;
			   break;
		   }else {  //没有转换成写锁,首先释放读锁,然后在拿到写锁
			lock.unlock(stamp);
			//获取写锁
			stamp=lock.writeLock();
		}
	  }
	   lock.unlock(stamp);
   }
   //获取乐观锁
   public void optimisticRead(){
	   	long stamp=lock.tryOptimisticRead();
	   	int c=balance;
	   	//可能出现写操作,需要判断
	   	if(!lock.validate(stamp)){
	   		//重新读取
	   		long readStamp= lock.readLock();
	   		c=balance;
	   		stamp=readStamp;
	   	}
	   	lock.unlock(stamp);
   }
   public void read(){
	  long stamp= lock.readLock();
	  int c=balance;
	  lock.unlockRead(stamp);
   }
   public void write(int value){
	 long stmp=  lock.writeLock();
	 balance +=value; 
	 lock.unlock(stmp);
   }
}

  

public class Demo77 {
   private int a;
   private boolean flag;
   public void write(){
	   //这两个数据之间没有数据依赖性,因此处理器会对这两行代码进行指令重排序
	   a=1;
	   flag=true;
   }
   public void reader(){
	   if(flag){
		   int b=a+1;
		   System.out.println(b);
	   }
   }
}

  

 当写一个volatile变量时,java 内存模型会把该线程对应的本地内存中的共享变量值刷新到主内存中

当读一个volatile变量时,Java内存模型会把当前线程对应的本地内存 中的共享变量置为无效,然后从主内从中读取共享变量

转载于:https://www.cnblogs.com/sunliyuan/p/11185263.html

### Java 并发容器概述 Java 提供了一系列用于支持并发操作的容器类,这些容器旨在提高多线程环境下的性能和安全性。以下是几种常见的并发容器以及它们的具体用途。 #### 1. **同步容器** 同步容器通过内置的 `synchronized` 关键字实现线程安全。然而,由于其锁粒度较大,在高并发场景下可能会成为瓶颈。主要代表有: - **Vector**: 这是一个动态数组,类似于现代的 `ArrayList`,但在每次访问时都会自动加锁以确保线程安全[^1]。 - **Hashtable**: 实现了 `Map` 接口,所有的方法都带有隐式的同步机制,因此适合单线程或多线程环境下使用,但由于全局锁定的原因,效率较低[^3]。 #### 2. **并发容器** 为了克服传统同步容器的不足之处,Java 引入了一组更高效的并发容器,采用细粒度锁或其他无锁算法来提升吞吐量。 - **ConcurrentHashMap**: 它是一种高度优化的线程安全哈希表结构。在 JDK 6 和 JDK 7 中,它依赖于分段锁技术;而在 JDK 8 及更高版本中,则改用基于 CAS 的非阻塞算法[^4]。下面展示了一个简单的例子: ```java import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); map.put(1, "Apple"); map.putIfAbsent(2, "Banana"); System.out.println(map.get(1)); // 输出 Apple } } ``` - **CopyOnWriteArrayList**: 当读取频率远高于写入频率时非常有用。它的核心思想是在执行任何修改操作之前先复制整个底层数组[^2]。尽管如此,频繁更新会带来较大的开销,所以需谨慎选用。 ```java import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class CopyOnWriteArrayListExample { public static void main(String[] args) { List<String> list = new CopyOnWriteArrayList<>(); list.add("Red"); list.add("Green"); for (String color : list) { System.out.println(color); if ("Green".equals(color)) { list.add("Blue"); // 不会引起 ConcurrentModificationException } } } } ``` - **BlockingQueue**: 常见的是 `LinkedBlockingQueue`, `ArrayBlockingQueue` 等形式,主要用于生产者消费者模式中的数据传递。此类队列提供等待功能以便当队列为空或者满的时候能够暂停调用方直到条件满足为止。 ```java import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class BlockingQueueExample { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> queue = new LinkedBlockingQueue<>(2); queue.put("Task A"); queue.put("Task B"); System.out.println(queue.take()); // 获取 Task A System.out.println(queue.poll()); // 非阻塞获取 Task B } } ``` ### 总结 上述介绍了一些常用的 Java 并发容器及其典型应用场景。每种容器都有各自的特点与适用范围,开发者应根据实际需求合理选择合适的工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值