线程池示例代码

package com.abc.test.thread;

public class SimpleThread extends Thread {

private boolean runningFlag;
private String agrs;

public boolean isRunningFlag() {
return runningFlag;
}

public synchronized void setRunningFlag(boolean runningFlag) {
this.runningFlag = runningFlag;
if (runningFlag) {
this.notify();
}
}

public String getAgrs() {
return agrs;
}

public void setAgrs(String agrs) {
this.agrs = agrs;
}

public SimpleThread(int threadNumber) {
runningFlag = false;
System.out.println("线程" + threadNumber + "启动了......");
}

public synchronized void run() {
try {
while (true) {
if (!runningFlag) {
this.wait();
} else {
System.out.println("处理" + getAgrs() + "......");
Thread.sleep(5000);
System.out.println("线程睡眠了......");
setRunningFlag(false);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}



package com.abc.test.thread;

import java.util.ArrayList;
import java.util.List;

public class ThreadPoolManager {
// 最大线程数
private int maxThread;

@SuppressWarnings("unchecked")
private List list;

public void setMaxThread(int maxThread) {
this.maxThread = maxThread;
}

@SuppressWarnings("unchecked")
public ThreadPoolManager(int maxThread){
this.setMaxThread(maxThread);
System.out.println("线程池启动了......");
list = new ArrayList();
for(int i=0;i<10;i++){
SimpleThread st = new SimpleThread(i);
list.add(st);
st.start();
}
}

public void process(String args){
int i;
for(i=0;i<list.size();i++){
SimpleThread curThread = (SimpleThread)list.get(i);
if(! curThread.isRunningFlag()){
System.out.println("线程"+i+"处理"+args);
curThread.setAgrs(args);
curThread.setRunningFlag(true);
return;
}
}
if(i == list.size()){
System.out.println("线程池已经满了,请等待另一个时间!");
}
}
}



package com.abc.test.thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestMultThreadPool {
public static void main(String[] args) {
try {
ThreadPoolManager manager = new ThreadPoolManager(10);
System.out.println("请输入字符:");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while ((str = bf.readLine()) != null) {
manager.process(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

你可能感兴趣的:(java,thread)