模拟实现线程池(线程数目为定值)和定时器
前言
昨天学习关于定时器的相关知识。今天花时间去模拟实现了一个定时器,同时也去模拟实现了一个线程池(线程数目为定值)。我感觉我收获了很多,对于线程的理解加深了。跟大家分享一下~
线程池和定时器(这个是主要)的实现
代码
线程池
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class MyThreadPool{//.创建任务队列private BlockingQueue<Runnable> blockingQueue=null;//.创建固定线程数目的线程池public MyThreadPool(int n) throws InterruptedException {//给任务队列给出容量大小blockingQueue=new ArrayBlockingQueue<>(1000);//创建线程for(int i=0;i<n;i++){Thread t=new Thread(()->{Runnable task= null;try {while(true){task = blockingQueue.take();task.run();}} catch (InterruptedException e) {throw new RuntimeException(e);}});
// t.setDaemon(true);t.start();}}//提交任务,将任务放入任务队列public void submit(Runnable task) throws InterruptedException {blockingQueue.put(task);}
}public class demo40 {public static void main(String[] args) throws InterruptedException {MyThreadPool myThreadPool=new MyThreadPool(10);//往线程池里面提交任务for(int i=0;i<100;i++){int id=i;myThreadPool.submit(()->{System.out.println(Thread.currentThread().getName()+" "+id);});}}
}
定时器
package Maybe;import java.util.PriorityQueue;class Mytimertask implements Comparable<Mytimertask>{private long time;private Runnable task;public Mytimertask(Runnable task,long time){this.task=task;this.time=time;}public void run(){task.run();}public long gettime(){return time;}@Overridepublic int compareTo(Mytimertask o) {return (int)(o.time-this.time);}
}
class Mytimer{Object locker=new Object();PriorityQueue<Mytimertask> queue=new PriorityQueue<>();public void schedule(Runnable task,long delay){synchronized(locker){Mytimertask task1=new Mytimertask(task,System.currentTimeMillis()+delay);queue.offer(task1);locker.notifyAll();}}public Mytimer(){Thread t=new Thread(()->{synchronized(locker){while(true){while(queue.isEmpty()){try {locker.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}Mytimertask task=queue.peek();if(task.gettime()>System.currentTimeMillis()){try {locker.wait(task.gettime()-System.currentTimeMillis());} catch (InterruptedException e) {throw new RuntimeException(e);}}else{task.run();queue.poll();}}}});t.start();}
}public class may {public static void main(String[] args) {Mytimer mytimer=new Mytimer();mytimer.schedule(new Runnable() {@Overridepublic void run() {System.out.println("hello 3000");}},3000);mytimer.schedule(new Runnable() {@Overridepublic void run() {System.out.println("hello 2000");}},2000);}
}
结语
本次的分享就到此为止了~ 最近要期末了,自学的东西要慢下来了,等期末过后,再猛猛地学。
希望期末周能快点过~~