JAVA线程池的实现及优先级设置
来源:优易学  2011-12-9 15:59:55   【优易学:中国教育考试门户网】   资料下载   IT书店


  Pooled.java:
  package org.loon.framework.util.test;
  /** */ /**
  *
  * Title: LoonFramework
  *
  *
  * Description:
  *
  *
  * Copyright: Copyright (c) 2007
  *
  *
  * Company: LoonFramework
  *
  *
  */

  public class Pooled extends Thread ... {
  private ThreadPool _pool;
  private Runnable _target;
  private boolean _shutdown = false ;
  private boolean _idle = false ;
  public Pooled(Runnable target) ... {
  super (target);
  }
  public Pooled(Runnable target, String name) ... {
  super (target, name);
  }
  public Pooled(Runnable target, String name, ThreadPool pool) ... {
  super (name);
  this ._pool = pool;
  this ._target = target;
  }
  public Pooled(String name) ... {
  super (name);
  }
  public Pooled(ThreadGroup group, Runnable target) ... {
  super (group, target);
  }
  public Pooled(ThreadGroup group, Runnable target, String name) ... {
  super (group, target, name);
  }
  public Pooled(ThreadGroup group, String name) ... {
  super (group, name);
  }
  public Runnable getTarget() ... {
  return this ._target;
  }
  public boolean isIdle() ... {
  return this ._idle;
  }
  public void run() ... {
  while ( ! this ._shutdown) ... {
  this ._idle = false ;
  if ( this ._target != null ) ... {
  this ._target.run();
  }
  this ._idle = true ;
  try ... {
  this ._pool.repool( this );
  synchronized ( this ) ... {
  wait();
  }
  } catch (InterruptedException ex) ... {
  System.err.println(ex.getMessage());
  }
  this ._idle = false ;
  }
  }
  public synchronized void setTarget(Runnable target) ... {
  this ._target = target;
  notifyAll();
  }
  public synchronized void shutDown() ... {
  this ._shutdown = true ;
  notifyAll();
  }
  }
  测试用类:
  package org.loon.framework.util.test;
  /** */ /**
  *
  Title: LoonFramework
  *
  Description:线程池测试
  *
  Copyright: Copyright (c) 2007
  *
  Company: LoonFramework
  */
  public class ThreadPoolTest ... {
  private static Runnable createRunnable( final int id) ... {
  return new Runnable() ... {
  public void run() ... {
  System.out.println( " 线程 " + id + " ,运行 " );
  try ... {
  Thread.sleep( 1000 );
  }
  catch (InterruptedException ex) ... { }
  System.out.println( " 线程 " + id + " ,结束 " );
  }
  } ;
  }
  public static void main(String[]args) ... {
  ThreadPool pool = ThreadPool.getInstance();
  pool.setDebug( true );
  for ( int i = 1 ; i <= 10 ; i ++ ) ... {
  // 根据数值,设定不同优先级
  if (i % 2 == 0 ) ... {
  pool.start(createRunnable(i), ThreadPool.PRIORITY_HIGH);
  } else ... {
  pool.start(createRunnable(i), ThreadPool.PRIORITY_LOW);
  }
  }
  System.out.println( " 线程池测试中…… " );
  System.out.println( " 线程池线程总数: " + pool.getThreadsCount());
  pool.shutDown();
  }
  }

上一页  [1] [2] 

责任编辑:小草

文章搜索:
 相关文章
热点资讯
热门课程培训