当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ThreadGroup checkAccess()用法及代码示例


ThreadGroup 类的 activeCount() 方法判断当前运行的线程是否有修改线程组的权限。

用法

public final void checkAccess()

返回

它不返回任何值。

异常

SecurityException:如果不允许当前线程访问线程组,则抛出此异常。

示例

class NewThread extends Thread 
{
    NewThread(String threadname, ThreadGroup tg)
    {
        super(tg, threadname);
    }
    public void run()
    {
        for (int i = 0; i < 10; i++) 
        {
            try
            {
                Thread.sleep(10);
            }
            catch (InterruptedException ex) 
            {
              System.out.println(Thread.currentThread().getName() + " interrupted");
            }
        }
        System.out.println(Thread.currentThread().getName() + " completed executing");
    }
} 
public class ThreadGroupCkeckAccessExp
{
    public static void main(String arg[]) throws InterruptedException, SecurityException
    {
        // creating a ThreadGroup
        ThreadGroup g1 = new ThreadGroup("Parent thread");
        // creating a child ThreadGroup for parent ThreadGroup
        ThreadGroup g2 = new ThreadGroup(g1, "child thread");

        // creating a thread 
        NewThread t1 = new NewThread("Thread-1", g1);
        t1.start();
        // creating another thread 
        NewThread t2 = new NewThread("Thread-2", g1);
        t2.start();
        
        // Check for access permission of current running thread
        g1.checkAccess();
        System.out.println(g1.getName() + " has access");
        g2.checkAccess();
        System.out.println(g2.getName() + " has access");
    }
}

输出:

Parent thread has access
child thread has access
Thread-1 finished executing
Thread-2 finished executing






相关用法


注:本文由纯净天空筛选整理自 Java ThreadGroup checkAccess() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。