JAVAlang.InheritableThreadLocal类及其示例

爪哇。lang.InheritableThreadLocal类扩展了ThreadLocal,以提供从父线程到子线程的值继承:创建子线程时,子线程接收父线程具有值的所有可继承线程局部变量的初始值。

null

父线程, ThreadLocal 默认情况下,变量对子线程不可用。 建造师 :

InheritableThreadLocal gfg_tl = new InheritableThreadLocal();

这是孩子们的班级 ThreadLocal 因此,所有的方法都存在于 ThreadLocal 默认情况下,可用于 可继承的线程本地 . 它只包含一种方法: 语法:

public Object childValue(Object parentValue) 

在子线程启动之前,在父线程内调用(重写)此方法。

  • 如果我们想让父线程、线程局部变量值对子线程可用,那么我们应该使用 可继承的线程本地
  • 默认情况下,子线程值与父线程值完全相同。但是我们可以通过覆盖 儿童价值观 方法

例子:

// Java program to illustrate parent thread, ThreadLocal variable
// by default not available to child thread
class ParentThread extends Thread {
public static ThreadLocal gfg_tl = new ThreadLocal();
public void run()
{
// setting the new value
gfg_tl.set( "parent data" );
// returns the ThreadLocal value associated with current thread
System.out.println( "Parent  Thread Value :" + gfg_tl.get());
ChildThread gfg_ct = new ChildThread();
gfg_ct.start();
}
}
class ChildThread extends Thread {
public void run()
{
// returns  the ThreadLocal value associated with current thread
System.out.println( "Child Thread Value :" + ParentThread.gfg_tl.get());
/* null (parent thread variable
thread local value is not available to child thread ) */
}
}
class ThreadLocalDemo {
public static void main(String[] args)
{
ParentThread gfg_pt = new ParentThread();
gfg_pt.start();
}
}


Output:
Parent Thread Value:parent data
Child Thread Value:null (by default initialValue is null)

// Java program to illustrate inheritance of customized value
// from parent thread to child thread
class ParentThread extends Thread {
// anonymous inner class  for overriding childValue method.
public static InheritableThreadLocal gfg_tl = new InheritableThreadLocal() {
public Object childValue(Object parentValue)
{
return "child data" ;
}
};
public void run()
{
// setting the new value
gfg_tl.set( "parent data" );
// parent data
System.out.println( "Parent Thread Value :" + gfg_tl.get());
ChildThread gfg_ct = new ChildThread();
gfg_ct.start();
}
}
class ChildThread extends Thread {
public void run()
{
// child data
System.out.println( "Child Thread Value :" + ParentThread.gfg_tl.get());
}
}
class ThreadLocalDemo {
public static void main(String[] args)
{
ParentThread gfg_pt = new ParentThread();
gfg_pt.start();
}
}


Output:
Parent Thread Value:parent data 
Child Thread Value:child data

第一种情况 :在上述程序中,如果我们用ThreadLocal替换InheritableThreadLocal,并且我们没有覆盖childValue方法,那么输出是:

Output:
Parent Thread Value: parent data 
Child Thread Value:null   (by default initialValue is null)

第二种情况 :在上面的程序中,如果我们正在维护InheritableThreadLocal,并且我们没有重写childValue方法,那么输出是:

Output :
Parent Thread Value:parent data 
Child Thread Value:parent data

第三种情况 :在上面的程序中,如果我们维护的是InheritableThreadLocal,并且我们还重写了childValue方法,那么输出是:

Output:
Parent Thread Value:parent data 
Child Thread Value:child data
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享