多线程demo

消费者-生产者模型

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * 生产者-消费者 信号量机制
 *
 */
public class ProductAndCustomer {

	private LinkedList<Integer> list = new LinkedList<>();
	private Semaphore product = new Semaphore(3);// 初始化缓冲区大小
	private Semaphore customer = new Semaphore(0);// 当前可消费数量

	/**
	 * 把资源放进缓冲区
	 * @param v
	 * @throws InterruptedException
	 */
	public void put(int v) throws InterruptedException {
		//缓冲区可用空间减一
		product.acquire();
		synchronized (list) {
			list.add(v);
		}
		//消费者可消费数量加一
		customer.release();
	}

	public int get() throws InterruptedException {
		int ret = -1;
		//消费者可消费数量减一
		customer.acquire();
		synchronized (list) {
			ret = list.pop();
		}
		//缓冲区可存放资源数量加一
		product.release();
		return ret;
	}

	
	public static void main(String[] args) {
		final ProductAndCustomer productAndCustomer = new ProductAndCustomer();
		
		/**
		 * 生产者线程
		 */
		for(int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					Random ran = new Random();
					while(true) {
						try {
							int nextInt = ran.nextInt(10);
							productAndCustomer.put(nextInt);
							System.out.println(Thread.currentThread().getName() + "=>" + nextInt);
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
			},"product-" + i).start();;
		}
		
		/**
		 * 消费者线程
		 */
		for(int i = 0; i < 5; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					Random ran = new Random();
					while(true) {
						try {
							System.out.println(Thread.currentThread().getName() + "=>" + productAndCustomer.get());
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
			},"customer-" + i).start();;
		}
	}
}

自定义线程池

import java.util.concurrent.LinkedBlockingQueue;

/**
 * 自定义线程池
 */
public class MyThreadPools {
	
	/**
	 * 任务队列-使用阻塞队列
	 */
	private LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
	
	
	public MyThreadPools(int size) {
		if(size < 1) {
			throw new RuntimeException("线程池大小至少为1");
		}
		for(int i = 0; i < size; i++) {
			new Thread(new ThreadTask(queue),"my-pool-" + i).start();
		}
	}
	
	public MyThreadPools(int size, String name) {
		if(size < 1) {
			throw new RuntimeException("线程池大小至少为1");
		}
		for(int i = 0; i < size; i++) {
			new Thread(new ThreadTask(queue), name + i).start();
		}
	}
	
	public void add(Runnable run) {
		queue.add(run);
	}
	
	class ThreadTask implements Runnable{
		private LinkedBlockingQueue<Runnable> queue = null;
		ThreadTask(LinkedBlockingQueue<Runnable> queue){
			this.queue = queue;
		}
		
		@Override
		public void run() {
			Runnable run = null;
			while(true) {
				try {
					//获取排队队列的任务,如果没有则阻塞,直到有任务进来
					run = queue.take();
					run.run();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}
	}
	
	
	public static void main(String[] args) {
		MyThreadPools pool = new MyThreadPools(3);
		
		for(int i = 0; i < 10; i++) {
			Thread thread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						System.out.println(Thread.currentThread().getName());
						Thread.sleep(1000);
					} catch (Exception e) {
						// TODO: handle exception
					}
					
				}
			});
			
			pool.add(thread);
		}
	}
}

自定义定时器

import java.util.Random;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 自定义简单定时器
 */
public class MyTimer {
	
	//使用优先级队列,把任务按照延迟时间来排队,首元素则是最近要执行的
	private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
	private Object lock = new Object(); //对象锁
	
	public void schdule(Runnable run, long time) {
		MyTask myTask = new MyTask(run, time);
		queue.add(myTask);
		//唤醒,如果有任务在阻塞,则进行唤醒,以便能再检查一次是否有任务可执行或者更新最近要执行的任务
		synchronized (lock) {
			lock.notifyAll();
		}
	}
	
	public MyTimer() {
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true) {
					try {
						MyTask myTask = queue.take();
						long time = myTask.getTime();
						long curr = System.currentTimeMillis();
						if(curr < time) {
							//时间未到,需要等待
							queue.add(myTask);
							//这里使用阻塞,如果不阻塞则一直空轮询--任务的执行时间未到
							synchronized (lock) {
								lock.wait(time - curr);
							}
							continue;
						}
						
						myTask.run();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				
			}
		}).start();
	}
	
	
	class MyTask implements Comparable<MyTask>{
		private Runnable run;
		private long time;
		
		MyTask(Runnable run, long time){
			this.run = run;
			this.time = time + System.currentTimeMillis();
		}
		
		@Override
		public int compareTo(MyTask o) {
			//升序
			return (int)(this.time - o.time);
		}

		public long getTime() {
			return time;
		}

		public void setTime(long time) {
			this.time = time;
		}
		
		
		public void run() {
			run.run();
		}
	}
	
	
	public static void main(String[] args) {
		MyTimer myTimer = new MyTimer();
		Random ran = new Random();
		for(int i = 0; i < 5; i++) {
			long time = ran.nextInt(10) * 1000;
			System.out.println(time);
			Thread thread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName());
				}
			});
			
			myTimer.schdule(thread, time);
		}
	}
	
}

自定义读写锁

/**
 * 自定义读写锁
 * 可重入
 * 写锁优先
 */
public class ReadAndWrite {
	private int reads = 0; //记录读锁
	private int writes = 0; //记录写锁
	private int writeRequests = 0; //记录是否有写锁排队--写优先
	private Thread currThread = null;
	
	public synchronized void readLock() {
		try {
			//如果有写锁或者有写锁请求,则等待
			while(writes > 0 || writeRequests > 0) {
				wait();
			}
			reads++;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void readUnlock() {
		reads--;
		notifyAll();
	}
	
	public synchronized void writeLock() {
		Thread t = Thread.currentThread();
		writeRequests++;
		try {
			//如果有读锁或者有其他写锁->不是该线程获取的写锁,则等待
			while(reads > 0 || (writes > 0 && currThread != t)) {
				wait();
			}
			if(currThread == null) {
				currThread = t;
			}
			writeRequests--;
			writes++;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void writeUnlock() {
		writes--;
		notifyAll();
	}
	
	static int j = 0;
	public static void main(String[] args) {
		final ReadAndWrite readAndWrite = new ReadAndWrite();
		
		/**
		 * 测试是否可重入
		 * 如果把对currThread变量相关的去掉,那么这里是死锁了
		 */
		readAndWrite.writeLock();
		readAndWrite.writeLock();
		System.out.println("===================");
		readAndWrite.writeUnlock();
		readAndWrite.writeUnlock();
		
		
		for(int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					while(true) {
						readAndWrite.writeLock();
						try {
							j++;
							System.out.println(Thread.currentThread().getName() + "=> " + j);
						} catch (Exception e) {
							// TODO: handle exception
						}finally {
							readAndWrite.writeUnlock();
						}
						
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
			},"write-" + i).start();
		}
		
		
		for(int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					while(true) {
						readAndWrite.readLock();
						try {
							System.out.println(Thread.currentThread().getName() + "=> " + j);
						} catch (Exception e) {
							// TODO: handle exception
						}finally {
							readAndWrite.readUnlock();
						}
						
						try {
							Thread.sleep(800);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
			},"read-" + i).start();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值