Java Thread setContextClassLoader()方法

java.lang.Thread.setContextClassLoader() 方法为线程设置上下文ClassLoader。创建线程时可以设置上下文ClassLoader。它允许线程的创建者通过getContextClassLoader提供适当的类加载器,以在加载类和资源时在线程中运行的代码。

1 语法

public void setContextClassLoader(ClassLoader cl)  

2 参数

cl: 这是线程的上下文ClassLoader。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.lang.Thread.setContextClassLoader()方法的例子
 */
public class Demo implements Runnable
{
    public void run()
    {
        System.out.println("Thread is running");
        // returns the context ClassLoader for currently running thread
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        // sets the context ClassLoader for currently running thread
        Thread.currentThread().setContextClassLoader(loader);
        System.out.println("Context ClassLoader = " + loader);
    }
    public static void main(String args[])
    {
        Demo g1 = new Demo();
        Thread t1 = new Thread(g1);
        // call run() method
        t1.start();
    }
}

输出结果为:

Thread is running
Context ClassLoader = sun.misc.Launcher$AppClassLoader@58644d46

热门文章

优秀文章