1.首先是一个MyMethod接口,里面只有一个方法看名字就知道了,就是我要做的事情。
Java代码
package com.test.thread;
public interface MyMethod {
public void dosomething();
}
2.然后是实现该方法的类,这个类可以自定义实现内容以完成需要放入线程池里面要做的具体事情。
Java代码
package com.test.thread;
public class MyMethodImpl implements MyMethod{
private int count;
public MyMethodImpl(int count) {
this.count = count;
}
@Override
public void dosomething() {
System.out.println("mymethod "+count+" in thread pool!");
}
}
3.好了接下来是个简单线程类继承了Thread类,作用就是实例化放进线程池里面的线程,包括往里面加入dosomething具体实现,以及一个while循环实现线程的等待wait()以及通知notify()的调用来实现线程池内某线程的等待还是执行状态。重点是标记running。
Java代码
package com.test.thread;
public class SimpleThread extends Thread{
private volatile boolean running;
private volatile int threadNumber;
private volatile MyMethod myMethod;
public SimpleThread() {
}
public SimpleThread(int number) {
this.threadNumber = number;
System.out.println("SimpleThread:"+threadNumber+" start!");
}
public boolean isRunning() {
return running;
}
public synchronized void setRunning(boolean running) {
this.running = running;
if(running)
this.notify();
}
public void setThreadNumber(int threadNumber) {
this.threadNumber = threadNumber;
}
public int getThreadNumber() {
return threadNumber;
}
public synchronized void setMyMethod(MyMethod myMethod) {
this.myMethod = myMethod;
}
public MyMethod getMyMethod() {
return myMethod;
}
public synchronized void dosomething(){
if(getMyMethod()!=null)
getMyMethod().dosomething();
}
@Override
public synchronized void run() {
try {
while (true) {
if (!isRunning()) {
System.out.println("SimpleThread:"+threadNumber+" wait!");
this.wait();
} else {
System.out.println("SimpleThread:"+threadNumber+" run!");
dosomething();
Thread.sleep(1000L);
setRunning(false);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4.最后是线程池类,我用一个list类进行线程存储,初始化线程池时根据poolsize初始化线程加进该list,然后直接设置running为false,这样启动start()后导致初始化时所有线程池里的线程都是wait()状态,等待被通知notify()。而execute方法则查找当前线程池中空闲线程,然后把dosomething交给这个线程去处理。
Java代码
package com.test.thread;
import java.util.ArrayList;
import java.util.List;
public class ThreadPool {
private int poolsize=10;
//工作线程
private List<SimpleThread> threads = new ArrayList<SimpleThread>();
public ThreadPool() {
init();
}
public ThreadPool(int poolsize) {
this.poolsize = poolsize;
init();
}
private void init(){
for(int i = 0;i < poolsize;i ++){
SimpleThread thread = new SimpleThread(i);
thread.setRunning(false);
threads.add(thread);
thread.start();
}
}
public synchronized void execute(MyMethod myMethod){
while(true){
for(SimpleThread thread : threads){
if(!thread.isRunning()){
thread.setMyMethod(myMethod);
thread.setRunning(true);
return;
}
}
}
}
public static void main(String[] args) {
ThreadPool pool = new ThreadPool();
for(int i=0;i<100;i++){
pool.execute(new MyMethodImpl(i));
}
}
}