Java教程

Java线程组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

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4