java多线程和队列实例

第一步:创建一个无边界自动回收的线程池,在此用 JDK提供的ExecutorService类

此线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。


package com.thread.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
	private static ExecutorService threadPool = null;
	public static ExecutorService getThreadPool(){
		if(threadPool==null){
			threadPool = Executors.newCachedThreadPool();
		}
		return 	threadPool;
	}

}

第二步:使用单例模式创建一个无界队列,并提供入队的方法

无界队列。使用无界队列(例如,不具有预定义容量的 LinkedBlockingQueue)将导致在所有corePoolSize 线程都忙时新任务在队列中等待。这样,创建的线程就不会超过 corePoolSize。(因此,maximumPoolSize的值也就无效了。)当每个任务完全独立于其他任务,即任务执行互不影响时,适合于使用无界队列;例如,在 Web页服务器中。这种排队可用于处理瞬态突发请求,当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增长的可能性。

package com.thread.test;

import java.util.concurrent.LinkedBlockingQueue;

public class TaskQueue {
	private static  LinkedBlockingQueue queues = null;
	
	public static LinkedBlockingQueue getTaskQueue(){
		if(queues==null){
			queues =  new LinkedBlockingQueue();
			System.out.println("初始化 队列");
		}
		return queues;
	}
	
	public static void add(Object obj){
		if(queues==null)
			queues =  getTaskQueue();
		queues.offer(obj);
		System.out.println("-------------------------------");
		System.out.println("入队:"+obj);
	}
}

第三步:提供一个入队的线程,实际使用中的生产者

package com.thread.test;

public class Produce implements Runnable {
	private static volatile int i=0;
	private static volatile boolean isRunning=true;

	public void run() {
		while(isRunning){
			TaskQueue.add(Integer.valueOf(i+""));
			Produce.i++;
			try {
				Thread.sleep(1*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

}

第四步:提供一个出队的线程,实际使用中的消费者

package com.thread.test;

public class Consumer implements Runnable {
	private static Consumer consumer;
	
	public static volatile boolean isRunning=true;
	public void run() {
		while(Thread.currentThread().isInterrupted()==false && isRunning)  
        {  
			try {
				System.out.println("出队"+TaskQueue.getTaskQueue().take());
				Thread.sleep(1*1000);  
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
		
	}
	public static Consumer getInstance(){
		if(consumer==null){
			consumer = new Consumer();
			System.out.println("初始化消费线程");
		}
		return consumer;
	}

}

第五步:启动生产消费策略

package com.thread.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;

public class Test {
	
	public static void main(String[] args) {
		ExecutorService threadPool = ThreadPool.getThreadPool();
		Produce consumer2 = new Produce();
		threadPool.execute(consumer2);
		Consumer consumer=Consumer.getInstance();
		threadPool.execute(consumer);
	}

}



好的,下面是一个简单的 Java 多线程队列实例,模拟队列实现排队叫号的过程: ```java import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class QueueExample { private Queue<Integer> queue = new LinkedList<>(); private Lock lock = new ReentrantLock(); private int currentTicketNumber = 0; public void addCustomer() { lock.lock(); try { queue.offer(currentTicketNumber++); System.out.println("新顾客取得号码:" + (currentTicketNumber - 1) + ",当前队列长度:" + queue.size()); } finally { lock.unlock(); } } public void serveCustomer() { lock.lock(); try { Integer ticketNumber = queue.poll(); if (ticketNumber == null) { System.out.println("队列为空,无法叫号"); } else { System.out.println("叫到号码:" + ticketNumber + ",当前队列长度:" + queue.size()); } } finally { lock.unlock(); } } public static void main(String[] args) { final QueueExample queueExample = new QueueExample(); // 开启 5 个线程模拟 5 个顾客取号 for (int i = 0; i < 5; i++) { new Thread(new Runnable() { @Override public void run() { queueExample.addCustomer(); } }).start(); } // 开启 3 个线程模拟 3 个服务员叫号 for (int i = 0; i < 3; i++) { new Thread(new Runnable() { @Override public void run() { queueExample.serveCustomer(); } }).start(); } } } ``` 这个例子中,我们定义了一个 `QueueExample` 类,其中有一个 `queue` 队列,用于存储所有顾客的票号。我们使用 `ReentrantLock` 类来实现线程安全。在 `addCustomer` 方法中,我们通过 `offer` 方法往队列中添加一个顾客的票号,并输出当前队列长度以及新顾客的票号。在 `serveCustomer` 方法中,我们通过 `poll` 方法从队列中获取一个顾客的票号,并输出当前队列长度以及叫到的顾客的票号。 在 `main` 方法中,我们开启了 5 个线程模拟 5 个顾客取号,以及 3 个线程模拟 3 个服务员叫号。你可以运行这个例子来看一下具体的输出结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值