专业的JAVA编程教程与资源

网站首页 > java教程 正文

JAVA并发-线程状态和线程组

temp10 2024-12-12 15:08:17 java教程 9 ℃ 0 评论

在Java中,线程有6种基本状态,理解这6种基本状态之间的关系可以让我们对多线程有更好的理解.如下图所示:

在Java中,所有的线程都存在于线程组中,每个线程组中可以包含多个线程或者线程组.运行下面的程序,从结果中可以看出默认的线程组层次结构.

JAVA并发-线程状态和线程组

system是Java中的根线程组.从system开始,有一层层的线程和线程组.类似目录结构.

/**
 * Java线程组的结构,见运行结果
 * @author Administrator
 *
 */
public class Main {
	public static void main(String [] args) {
		Thread.currentThread.getThreadGroup.getParent.list;
		Thread.currentThread.getThreadGroup.list;
	}	
}

下面的程序中实现当一个线程运行结束时,结束其他的线程.这个需求也可以用Executor框架来完成.不过显然用线程组是容易的.

/**
 * 实现当一个线程运行结束时,结束其他的线程
 * @author Administrator
 *
 */
public class Main {
	public static void main(String [] args) throws InterruptedException{
		ThreadGroup threadGroup = new ThreadGroup("Searcher");
		
		
		for(int i=0;i<5;i++){
			new Thread(threadGroup,new Task,"t"+(i+1)).start;
		}
		
		System.out.println(threadGroup.activeCount);
		threadGroup.list;
		
		Thread.sleep(1000);
		waitFinish(threadGroup);
		
		threadGroup.interrupt;
	}
	
	private static void waitFinish(ThreadGroup threadGroup) {
		while (threadGroup.activeCount>5) {
		}
		System.out.println("有一个结束了");
	}
}

class Task implements Runnable {
	public void run {
		for(int i=0;i<Integer.MAX_VALUE/100;i++){
			System.out.print(i+" ");
			if(Thread.currentThread.isInterrupted)
				break;
		}
		System.out.println(Thread.currentThread.getName);
	}
}

在JAVA多线程编程时,通过为一个线程对象或者一个线程类设置UncaughtExceptionHandler可以实现捕获run方法内的运行时异常.

下面的例子是捕获线程内的运行时异常:

public class Main {
	public static void main(String [] args) {
		
		for(int i=0;i<3;i++){
			final int flag=i;
			MyThread myThread=new MyThread;
			myThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler {
				@Override
				public void uncaughtException(Thread arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					System.out.println("mythead发生异常!"+flag);
					
				}
			});
			myTHread.start;
		}
	}
}

class MyThread extends Thread{
	public void run{
		String str=null;
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace;
		}
		System.out.println(str.hashCode);
	}
}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表