本人近来需要在servlet里另起线程池,以便控制,因为servlet的线程是不为我们能控制的,所以无奈之下,使用了ThreadPoolExecutor类。
但是有些任务需要在自己创建的线程池里执行完了,servlet的程序才继续执行。
本来想着用join(),但是线程池的线程引用拿不到,如果在线程池里设置成员变量,又会引起线程不安全(事实上,join()了也没用,因为线程池的线程是不会结束的,join()等待是无结果的)。
苦于成员变量不能设置,局部变量又不可以夸类传递。。
方法一:如果用某个变量控制循环等待,可以实现功能,但不是我要的结果,因为这样的主线程并不是挂起,只是不断循环等待的,一样需要耗费资源,如果线程过多会非常浪费资源。
方法二:在执行任务的程序的run()方法的最后用wait/notify,唤醒主线程,真正实现了异步,主线程并不多耗费资源。缺点是不够灵活,例如:更改了执行的任务,就必须在新任务的run()方法后加入唤醒操作,不能做到与任务无关,所以有了第三种方法。
方法三:用wait/notify和挂钩程序及反射机制的应用,实现了线程池间的通信控制。下面的程序就是介绍第三种方法的。
主程序(main函数可模拟是servlet的doPost(),只要保证该类线程安全即可):
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test {
private PausableThreadPoolExecutor threadPool;
public Test() {
threadPool = new
PausableThreadPoolExecutor(10, 20, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(8), new ThreadPoolExecutor.DiscardOldestPolicy());
}
public static void main(String[] args) throws InterruptedException {
Test t = new Test();
Object o = new Object();
//提交任务给线程池,包括了下句用到的对象锁o。
t.threadPool.execute(new newThread(o));
synchronized(o){
o.wait();//等待别的线程唤醒
}
System.out.printl("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}
}
执行的任务(所有的新任务只要继承TestThread和实现Runnable接口,而不用改run()方法,真正实现了与任务无关的异步多线程通信控制。)
class newThread extends TestThread implements Runnable{
newThread(Object o) {
super(o);
// TODO Auto-generated constructor stub
}
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class TestThread {
Object o = null;
TestThread(Object o) {
this.o = o;
}
public Object getO() {//用于获取主线程的锁对象
return o;
}
}
挂钩程序
class PausableThreadPoolExecutor extends ThreadPoolExecutor {
PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler){
super(corePoolSize, maximumPoolSize, keepAliveTime,unit,workQueue,handler) ;
}
//执行Execute前调用的函数
protected void beforeExecute(Thread t,Runnable r){
super.beforeExecute(t, r);
}
//执行Execute后调用的函数
protected void afterExecute(Runnable r,Throwable t){
super.afterExecute(r,t);
//System.out.println(r.getClass().getName());
//运用反射机制和挂钩程序实现线程池的嵌套控制
try {
Method m = r.getClass().getMethod("getO", null);//得到getO方法
Object o = m.invoke(r, null);//执行运行实例的getO方法,得到对象o的锁
synchronized(o){
o.notify();//唤醒主程序
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
最后,关于线程的安全性作一点说明。。大家注意到PausableThreadPoolExecutor类没有成员变量,因为这是由多线程访问的类;主程序也只有线程池一个成员变量,即使主线程是多线程的话,共享这个成员变量也是合理的,因为池就只有一个,除此之外主线程也不该再有其他成员变量;而newThread的超类TestThread类可以拥有成员变量,因为每次提交新任务给线程池的时候都会new一个新的实例,不存在多线程访问的问题。
打印结果:
1 2 3 4 5 6 7 8 9 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
分析:先执行了线程池的打印操作1~9,最后唤醒主线程打印<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
摘自:http://www.iteye.com/topic/567977
view_base project
2个image view 1个page Control
代码:
- (void) pageTurning: (UIPageControl *) pageController
{
//---get the page number you can turning to---
NSInteger nextPage = [pageController currentPage];
switch (nextPage) {
case 0:
[tempImageView setImage:[UIImage imageNamed:@"iMac_old.jpeg"]];
break;
case 1:
[tempImageView setImage:[UIImage imageNamed:@"iMac.jpeg"]];
break;
case 2:
[tempImageView setImage:[UIImage imageNamed:@"Mac8100.jpeg"]];
break;
case 3:
[tempImageView setImage:[UIImage imageNamed:@"MacPlus.jpeg"]];
break;
case 4:
[tempImageView setImage:[UIImage imageNamed:@"MacSE.jpeg"]];
break;
default:
break;
}
//---switch the two imageview views---
if (tempImageView.tag==0) { //---imageView1---
tempImageView = imageView2;
bgImageView = imageView1;
}
else { //---imageView2---
tempImageView = imageView1;
bgImageView = imageView2;
}
//---animate the two views flipping---
[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft
forView:tempImageView cache:YES];
[tempImageView setHidden:YES];
[UIView commitAnimations];
[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight
forView:bgImageView cache:YES];
[bgImageView setHidden:NO];
[UIView commitAnimations];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
//---initialize the first imageview to display an image---
[imageView1 setImage:[UIImage imageNamed:@"iMac_old.jpeg"]];
tempImageView = imageView2;
//---make the first imageview visible and hide the second---
[imageView1 setHidden:NO];
[imageView2 setHidden:YES];
//---add the event handler for the page control---
[pageControl addTarget:self action:@selector(pageTurning:)
forControlEvents:UIControlEventValueChanged];
[super viewDidLoad];
}
朋友让我帮忙写个程序从文本文档中导入数据到oracle数据库中,技术上没有什么难度,文档的格式都是固定的只要对应数据库中的字段解析就行了,关键在于性能。
数据量很大百万条记录,因此考虑到要用多线程并发执行,在写的过程中又遇到问题,我想统计所有子进程执行完毕总共的耗时,在第一个子进程创建前记录当前时间用System.currentTimeMillis()在最后一个子进程结束后记录当前时间,两次一减得到的时间差即为总共的用时,代码如下
long tStart = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + "开始");//打印开始标记
for (int ii = 0; ii < threadNum; ii++) {//开threadNum个线程
Runnable r = new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + "开始");
//做一些事情... ...
System.out.println(Thread.currentThread().getName() + "结束.");
}
}
Thread t = new Thread(r);
t.start();
}
System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记
long tEnd = System.currentTimeMillis();
System.out.println("总共用时:"+ (tEnd - tStart) + "millions");
结果是几乎在for循环结束的瞬间就执行了主线程打印总共用时的语句,原因是所有的子线程是并发执行的,它们运行时主线程也在运行,这就引出了一个问题即本文标题如何"让主线程等待所有子线程执行完毕"。试过在每个子线程开始后加上t.join(),结果是所有线程都顺序执行,这就失去了并发的意义了,显然不是我想要的。
网上Google了很久也没有找到,难道就没有人遇到过这种需求吗?还是这个问题太简单了?无耐只得自己想办法了...
最后我的解决办法是,自定义一个ImportThread类继承自java.lang.Thread,重载run()方法,用一个List属性保存所有产生的线程,这样只要判断这个List是否为空就知道还有没有子线程没有执行完了,类代码如下:
public class ImportThread extends Thread {
private static List<Thread> runningThreads = new ArrayList<Thread>();
public ImportThread() {
}
@Override
public void run() {
regist(this);//线程开始时注册
System.out.println(Thread.currentThread().getName() + "开始...");//打印开始标记
//做一些事情... ...
unRegist(this);//线程结束时取消注册
System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记
}
public void regist(Thread t){
synchronized(runningThreads){
runningThreads.add(t);
}
}
public void unRegist(Thread t){
synchronized(runningThreads){
runningThreads.remove(t);
}
}
public static boolean hasThreadRunning() {
return (runningThreads.size() > 0);//通过判断runningThreads是否为空就能知道是否还有线程未执行完
}
}
主线程中代码:
long tStart = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + "开始");//打印开始标记
for (int ii = 0; ii < threadNum; ii++) {//开threadNum个线程
Thread t = new ImportThread();
t.start();
}
while(true){//等待所有子线程执行完
if(!ImportThread.hasThreadRunning()){
break;
}
Thread.sleep(500);
}
System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记
long tEnd = System.currentTimeMillis();
System.out.println("总共用时:"+ (tEnd - tStart) + "millions");
打印的结果是:
main开始
Thread-1开始...
Thread-5开始...
Thread-0开始...
Thread-2开始...
Thread-3开始...
Thread-4开始...
Thread-5结束.
Thread-4结束.
Thread-2结束.
Thread-0结束.
Thread-3结束.
Thread-1结束.
main结束.
总共用时:20860millions
可以看到main线程是等所有子线程全部执行完后才开始执行的。
==================================================以下为第二次编辑===============================================
上面的方法有一个隐患:如果线程1开始并且结束了,而其他线程还没有开始此时runningThreads的size也为0,主线程会以为所有线程都执行完了。解决办法是用一个非简单类型的计数器来取代List型的runningThreads,并且在线程创建之前就应该设定好计数器的值。
MyCountDown类
public class MyCountDown {
private int count;
public MyCountDown(int count){
this.count = count;
}
public synchronized void countDown(){
count--;
}
public synchronized boolean hasNext(){
return (count > 0);
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
ImportThread类
public class ImportThread extends Thread {
private MyCountDown c;
public ImportThread(MyCountDown c) {
this.c = c;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "开始...");//打印开始标记
//Do something
c.countDown();//计时器减1
System.out.println(Thread.currentThread().getName() + "结束. 还有" + c.getCount() + " 个线程");//打印结束标记
}
}
主线程中
System.out.println(Thread.currentThread().getName() + "开始");//打印开始标记
MyCountDown c = new MyCountDown(threadNum);//初始化countDown
for (int ii = 0; ii < threadNum; ii++) {//开threadNum个线程
Thread t = new ImportThread(c);
t.start();
}
while(true){//等待所有子线程执行完
if(!c.hasNext()) break;
}
System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记
打印结果:
main开始
Thread-2开始...
Thread-1开始...
Thread-0开始...
Thread-3开始...
Thread-5开始...
Thread-4开始...
Thread-5结束. 还有5 个线程
Thread-1结束. 还有4 个线程
Thread-4结束. 还有3 个线程
Thread-2结束. 还有2 个线程
Thread-3结束. 还有1 个线程
Thread-0结束. 还有0 个线程
main结束.
更简单的方法:使用java.util.concurrent.CountDownLatch代替MyCountDown,用await()方法代替while(true){...}
ImportThread类
public class ImportThread extends Thread {
private CountDownLatch threadsSignal;
public ImportThread(CountDownLatch threadsSignal) {
this.threadsSignal = threadsSignal;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "开始...");
//Do somethings
threadsSignal.countDown();//线程结束时计数器减1
System.out.println(Thread.currentThread().getName() + "结束. 还有" + threadsSignal.getCount() + " 个线程");
}
}
主线程中
CountDownLatch threadSignal = new CountDownLatch(threadNum);//初始化countDown
for (int ii = 0; ii < threadNum; ii++) {//开threadNum个线程
final Iterator<String> itt = it.get(ii);
Thread t = new ImportThread(itt,sql,threadSignal);
t.start();
}
threadSignal.await();//等待所有子线程执行完
System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记
打印结果:
main开始
Thread-1开始...
Thread-0开始...
Thread-2开始...
Thread-3开始...
Thread-4开始...
Thread-5开始...
Thread-0结束. 还有5 个线程
Thread-1结束. 还有4 个线程
Thread-4结束. 还有3 个线程
Thread-2结束. 还有2 个线程
Thread-5结束. 还有1 个线程
Thread-3结束. 还有0 个线程
main结束.
摘自:http://www.iteye.com/topic/581476