多线程-进程池

package bao;

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 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.每个线程都没有跑完。

    2.ThreadGroup 可以扫描出有多少个active 线程。

 

 

代码源于: http://www.cnblogs.com/yy2011/archive/2011/05/05/2037564.html

感谢。

 

 

1 class MyThread extends Thread {
2 boolean stopped;
3
4 MyThread(ThreadGroup tg, String name) {
5 super(tg, name);
6 stopped =false;
7 }
8
9 publicvoid run() {
10 System.out.println(Thread.currentThread().getName() +" starting.");
11 try {
12 for (int i =1; i <1000; i++) {
13 System.out.print(".");
14 Thread.sleep(250);
15 synchronized (this) {
16 if (stopped)
17 break;
18 }
19 }
20 } catch (Exception exc) {
21 System.out.println(Thread.currentThread().getName() +" interrupted.");
22 }
23 System.out.println(Thread.currentThread().getName() +" exiting.");
24 }
25
26 synchronizedvoid myStop() {
27 stopped =true;
28 }
29 }
30
31 publicclass Main {
32 publicstaticvoid main(String args[]) throws Exception {
33 ThreadGroup tg =new ThreadGroup("My Group");
34
35 MyThread thrd =new MyThread(tg, "MyThread #1");
36 MyThread thrd2 =new MyThread(tg, "MyThread #2");
37 MyThread thrd3 =new MyThread(tg, "MyThread #3");
38
39 thrd.start();
40 thrd2.start();
41 thrd3.start();
42
43 Thread.sleep(1000);
44
45 System.out.println(tg.activeCount() +" threads in thread group.");
46
47 Thread thrds[] =new Thread[tg.activeCount()];
48 tg.enumerate(thrds);
49 for (Thread t : thrds)
50 System.out.println(t.getName());
51
52 thrd.myStop();
53
54 Thread.sleep(1000);
55
56 System.out.println(tg.activeCount() +" threads in tg.");
57 tg.interrupt();
58 }
59 }
posted @ 2012-09-03 19:01  LLLeon  阅读(168)  评论(0编辑  收藏  举报