描述
这个java.lang.ThreadGroup.interrupt()方法中断此线程组中的所有线程。
声明
以下是声明java.lang.ThreadGroup.interrupt()方法
public final void interrupt()
参数
NA
返回值
此方法不返回任何值。
异常
SecurityException- 如果当前线程不被允许访问该线程组或线程组中的任何线程。
示例
下面的例子展示了 java.lang.ThreadGroup.interrupt() 方法的用法。
package com.tutorialspoint;
import java.lang.*;
class newThread extends Thread {
boolean stop;
newThread(ThreadGroup group, String name) {
super(group, name);
stop = false;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " starting.");
try {
for(int i = 1; i < 1000; i++) {
Thread.sleep(500);
synchronized(this) {
if(stop)
break;
}
}
} catch(Exception e) {
System.out.print(Thread.currentThread().getName());
System.out.println(" interrupted.");
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}
synchronized void stopFunc() {
stop = true;
}
}
public class ThreadGroupDemo {
public static void main(String args[]) throws Exception {
ThreadGroup group = new ThreadGroup("new Group");
newThread t1 = new newThread(group, "Thread1");
newThread t2 = new newThread(group, "Thread2");
// this will call run() method
t1.start();
t2.start();
Thread.sleep(1000);
// it shows current active threads in Thread Group
System.out.println(group.activeCount() + " threads in thread group...");
// returns the number of thread groups
Thread th[] = new Thread[group.activeCount()];
group.enumerate(th);
for(Thread t:th)
System.out.println(t.getName());
t1.stopFunc();
Thread.sleep(1000);
System.out.println(group.activeCount() + " threads in thread group...");
// thread group interrupted
group.interrupt();
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
Thread1 starting. Thread2 starting. 2 threads in thread group... Thread1 Thread2 Thread1 exiting. 1 threads in thread group... Thread2 interrupted. Thread2 exiting.
相关用法
- Java Java.lang.ThreadGroup.isDestroyed()用法及代码示例
- Java Java.lang.ThreadGroup.isDaemon()用法及代码示例
- Java Java.lang.ThreadGroup.uncaughtException()用法及代码示例
- Java Java.lang.ThreadGroup.parentOf()用法及代码示例
- Java Java.lang.ThreadGroup.getName()用法及代码示例
- Java Java.lang.ThreadGroup.destroy()用法及代码示例
- Java Java.lang.ThreadGroup.list()用法及代码示例
- Java Java.lang.ThreadGroup.checkAccess()用法及代码示例
- Java Java.lang.ThreadGroup.enumerate()用法及代码示例
- Java Java.lang.ThreadGroup.toString()用法及代码示例
- Java Java.lang.ThreadGroup.setDaemon()用法及代码示例
- Java Java.lang.ThreadGroup.activeCount()用法及代码示例
- Java Java.lang.ThreadGroup.getParent()用法及代码示例
- Java Java.lang.ThreadGroup.getMaxPriority()用法及代码示例
- Java Java.lang.ThreadGroup.setMaxPriority()用法及代码示例
- Java Java.lang.Thread.run()用法及代码示例
- Java Java.lang.Thread.isDaemon()用法及代码示例
- Java Java.lang.Thread.checkAccess()用法及代码示例
- Java Java.lang.Thread.getState()用法及代码示例
- Java Java.lang.Thread.yield()用法及代码示例
注:本文由纯净天空筛选整理自 Java.lang.ThreadGroup.interrupt() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。