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


Java Executor privilegedThreadFactory()用法及代码示例


Executors 类的 privilegedThreadFactory() 方法返回一个线程工厂,用于创建与当前线程具有相同权限的新线程。该工厂使用与 defaultThreadFactory() 相同的设置创建线程,另外将新线程的 AccessControlContext 和 contextClassLoader 设置为与调用此特权线程工厂方法的线程相同。

用法

public static ThreadFactory privilegedThreadFactory()

参数

没有传递参数。

返回

一个线程工厂

抛出

访问控制异常

例子1

//import statement
  
    import java.util.concurrent.Executors;  
    import java.util.concurrent.ThreadFactory;  
      
    public class ExecutorsprivilegedThreadFactoryExample1  {  
       
        public static void main(String[] args) {  
            ThreadFactory thrdfctry = Executors.defaultThreadFactory();  
            Thread t = thrdfctry.newThread(new Mythrd3());  
            t.start();        
        }   
    }  
      
    class Mythrd3 implements Runnable {  
       
        @Override  
        public void run() {  
            System.out.println("Running thread concurrently");  
        }  
    }

输出:

Running thread concurrently

例子2

import java.util.Date;
    import java.util.concurrent.Executors;  
    import java.util.concurrent.ThreadFactory;  
      
    public class ExecutorsprivilegedThreadFactoryExample2  {  
       
        public static void main(String[] args) {  
            ThreadFactory thrdfctry = Executors.privilegedThreadFactory();
            for(int i=0 ; i<=5 ; i++){
            Thread t = thrdfctry.newThread(new Mythrd5());  
             t.start();        
        }   
    }  
    }
    class Mythrd5 implements Runnable {  
       
        @Override  
        public void run() {  
            System.out.println("Running thread concurrently ::" +  new Date());  
        }  
    }

输出:

Running thread concurrently ::Sun Mar 17 03:24:04 IST 2019
Running thread concurrently ::Sun Mar 17 03:24:04 IST 2019
Running thread concurrently ::Sun Mar 17 03:24:04 IST 2019
Running thread concurrently ::Sun Mar 17 03:24:04 IST 2019
Running thread concurrently ::Sun Mar 17 03:24:04 IST 2019
Running thread concurrently ::Sun Mar 17 03:24:04 IST 2019




相关用法


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