Java ThreadGroup checkAccess()方法

ThreadGroup類的activeCount()方法確定當前運行的線程是否具有修改線程組的許可權。

語法

public final void checkAccess()

返回
它不會返回任何值。

異常

  • SecurityException:如果不允許當前線程訪問線程組,則拋出此異常。

示例

package com.zaixian;

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 completed executing
Thread-2 completed executing

上一篇: Java線程組 下一篇: Java關閉掛鉤(shutdown hook)