多线程相关的Demo

多线程相关的Demo

  • CountDownLatch Demo

    他的作用是,某一个线程等待其他线程执行完才会执行。其他线程的数量取决于CountDownLatch构造函数的值。主要用在一个项目,某些框架要等其他框架加载后在执行。

    package com.attackOnOffer.Thread;
    
    import java.util.concurrent.CountDownLatch;
    
    public class CountDownDemo {
    	public static CountDownLatch countDown = new CountDownLatch(10);
    	
    	static class Test implements Runnable{
    		@Override
    		public void run() {
    			for (int syso = 0; syso < 10; syso++) {
    				System.out.println(syso + "子框架加载成功!");
    				try {
    					Thread.sleep(1000);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				countDown.countDown(); // 计数减1
    			}
    		}
    	}
    	
    	static class Test1 implements Runnable{
    		@Override
    		public void run() {
    			try {
    				countDown.await(); // 等待计数为0
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			System.out.println("加载主框架");
    		}
    	}
    	
    	public static void main(String[] args) {
    		new Thread(new Test()).start();
    		new Thread(new Test1()).start();
    	}
    }
    

在这里插入图片描述

  • 最简单的线程池demo–主要体现线程复用

    package com.attackOnOffer.Thread;
    
    import java.util.HashSet;
    import java.util.Set;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    
    public class ThreadPoolDemo {
    	private int work_num = 0;
    	private static int WORK_NUM = 3;
        // BlockingQueue   ArrayBlockingQueue
    	private BlockingQueue<Runnable> queue = null; // 这个队列中的是runnable和workThread不一样,workThread是一个专门用来复用线程的类
    	private Set<WorkThread> workSet = null;
    	
    	public ThreadPoolDemo() {
    		this(WORK_NUM);
    	}
    	
    	public ThreadPoolDemo(int work_num) {
    		this.work_num = work_num;
    		workSet = new HashSet<ThreadPoolDemo.WorkThread>(work_num);
    		queue = new ArrayBlockingQueue<Runnable>(work_num); // arrayBlockingQueue
    		for (int i = 0; i < work_num; i++) {
    			WorkThread work = new WorkThread();
    			work.start();
    			workSet.add(work);
    		}
    	}
    	
    	public void execute(Runnable a) {
    		try {
    			queue.add(a); // 只是添加到队列中
    		} catch (Exception e) {
    			
    		}
    	}
    	
    	public void destroy() {
    		if(workSet == null || workSet.isEmpty()) return ;
    		for (WorkThread work : workSet) {
    			work.stopWork();
    			work = null;
    		}
    		workSet.clear();
    	}
    	
        // 这个类似专门用来 不断去队列中拿runnable对象的,而队列中的对象是runnable。
    	private class WorkThread extends Thread{
    		@Override
    		public void run() {
    			while(!isInterrupted()) {
    				try {
    					Runnable take = queue.take();
    					if(take != null) {
    						take.run();
    					}
    					take = null; // help gc;
    				} catch (Exception e) {
    					interrupt();
    				}
    			}
    		}
    		
    		public void stopWork() {
    			interrupt();  // 就这样停止
    		}
    	}
    }
    
  • 实现一个消费者和生产模式

    // 本质就是先获取锁,如果不满足条件就wait释放,最后生产或者消费完了以后,notifyall其他线程.

    package com.attackOnOffer.Thread;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ProducerAndConsumerDemo {
    	private static List<String> list = new ArrayList<String>();
    	
    	private int max_num = 10;
    	
    	public void putString(int num) {
    		synchronized (list) { // 锁住list
    			while(list.size() + num> max_num) {
    				try {
    				System.out.println(Thread.currentThread().getName() + "list库存大于最大值,无法继续生产" );
    					list.wait(); // wait 会马上释放锁  使用list的wait
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			int i = 0;
    			while(i < num){
    				i++;
    				list.add(String.valueOf(i));
    			}
    			System.out.println(Thread.currentThread().getName() + "生产后此时list的容量"+list.size());
    			list.notifyAll(); // 使用list的notifyall
    		}
    	}
    	
    	public void removeString(int num) {
    		synchronized(list) {
    			while(list.size() < num) {
    				System.out.println(Thread.currentThread().getName() +  "当前的库存为0,无法消费");
    				try {
    					list.wait();
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			while(num > 0) {
    				list.remove(list.size() -1);
    				num--;
    			}
    			System.out.println(Thread.currentThread().getName() +  "消费后list的容量"+list.size());
    			list.notifyAll();
    		}
    	}
    	
    	static class Produer implements Runnable{
    		@Override
    		public void run() {
    			ProducerAndConsumerDemo a = new ProducerAndConsumerDemo();
    			a.putString(10);
    		}
    	}
    	
    	static class Consumer implements Runnable{
    		@Override
    		public void run() {
    			ProducerAndConsumerDemo a = new ProducerAndConsumerDemo();
    			a.removeString(8);
    		}
    	}
    	
    	public static void main(String[] args) {
    		new Thread(new Consumer()).start();
    		new Thread(new Consumer()).start();
    		new Thread(new Produer()).start();
    		new Thread(new Produer()).start();
    	}	
    }
    
  • 阻塞队列的实现

    package com.attackOnOffer.Thread;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class BlockingQueueDemo {
    	private List<String> list = null; // 本身一定是一个容器
    	private volatile int capacity = 0;
    	private volatile int size = 0; // 用来记录当前队列中的数量
    	private ReentrantLock lock = new ReentrantLock();
    	private Condition isFull =lock.newCondition();
    	private Condition isNull =lock.newCondition();
    	
    	public BlockingQueueDemo(int cap) {
    		this.capacity = cap;
    		list = new ArrayList<String>();
    	}
    	
    	public void put(String demo) {
    		lock.lock();
    		try {
    			while(size >= capacity) {
    				try {
    					System.out.println("队列满了 不要放了!!!");
    					isFull.await();
    				} catch (InterruptedException e) {
    					isFull.signal();
    					e.printStackTrace();
    				}
    			}
    			list.add(demo);
    			size++;
    			isNull.signal();
    		} finally {
    			lock.unlock();
    		}
    	}
    	
    	public void get() {
    		lock.lock();
    		try {
    			while(size <= 0) {
    				System.out.println("队列空了,拿不出东西");
    				try {
    					isNull.await();
    				} catch (InterruptedException e) {
    					isNull.signal();
    					e.printStackTrace();
    				}
    			}
    			list.remove(0);
    			size--;
    			isFull.signal();
    		} finally {
    			lock.unlock();
    		}
    	}
    	
    	public static void main(String[] args) {
    		// 我就不用线程来消费 生产了。。。偷懒
    		BlockingQueueDemo queue = new BlockingQueueDemo(3);
    		queue.put("1");
    		queue.put("1");
    		queue.put("1");
    		queue.put("1");
    		queue.get();
    		queue.get();
    		queue.get();
    		queue.get();
    		queue.get();
    	}
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值