ThreadGroup_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > ThreadGroup

ThreadGroup

 2011/10/10 8:06:09  schel  http://schel.iteye.com  我要评论(0)
  • 摘要:java.lang.ThreadGroup,ThreadGroup有很多优势,最重要的一点就是它可以对线程进行遍历,知道那些线程已经运行完毕,还有那些线程在运行。关于ThreadGroup的使用代码如下:classMyThreadextendsThread{booleanstopped;MyThread(ThreadGrouptg,Stringname){super(tg,name);stopped=false;}publicvoidrun(){System.out.println
  • 标签:thread
java.lang.ThreadGroup,ThreadGroup有很多优势,最重要的一点就是它可以对线程进行遍历,知道那些线程已经运行完毕,还有那些线程在运行。关于ThreadGroup的使用代码如下:
class MyThread extends Thread { 
	boolean stopped; 
	MyThread(ThreadGroup tg, String name) { 
		super(tg, name);
		stopped = false; 
	} 
	public void run() {
		System.out.println(Thread.currentThread().getName() + " starting.");
		try {
			for (int i = 1; i < 1000; i++) {
				System.out.print(".");
				Thread.sleep(250);
				synchronized (this) {
					if (stopped)break;
				}
			}
		} catch (Exception exc) {
			System.out.println(Thread.currentThread().getName() + " interrupted.");
		}
		System.out.println(Thread.currentThread().getName() + " exiting.");
	}
	synchronized void myStop() {
		stopped = true;
	}
}
public class Main {
	public static void main(String args[]) throws Exception {
		ThreadGroup tg = new ThreadGroup("My Group");
		MyThread thrd = new MyThread(tg, "MyThread #1");
		MyThread thrd2 = new MyThread(tg, "MyThread #2");
		MyThread thrd3 = new MyThread(tg, "MyThread #3");
		thrd.start();
		thrd2.start();
		thrd3.start();
		Thread.sleep(1000);
		System.out.println(tg.activeCount() + " threads in thread group.");
		Thread thrds[] = new Thread[tg.activeCount()];
		tg.enumerate(thrds);
		for (Thread t : thrds)
			System.out.println(t.getName());
		thrd.myStop();
		Thread.sleep(1000);
		System.out.println(tg.activeCount() + " threads in tg.");
		tg.interrupt();
	}
}

1.ThreadGroup可以遍历线程,知道那些线程已经运行完毕,那些还在运行 

2.可以通过ThreadGroup.activeCount知道有多少线程从而可以控制插入的线程数
http://www.mechw.com
发表评论
用户名: 匿名