當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。