java 多线程(threadlocal)

package com.example;

import java.util.Random;

public class App {
    
    public static class MyRunnable1 implements Runnable {
        //ThreadLocal是一个线程局部变量
        private ThreadLocal<String> threadlocal 
            = new ThreadLocal<String>();
 
        @Override
        public void run() {
            //threadlocal 包含方法:
            //set:创建一个线程本地变量
            //remove:移除该本地变量
            //get:获取该本地变量的值
            //在hibernate中被用于本地session管理            
            threadlocal.set("Name:"+new Random().nextInt(10));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : " + threadlocal.get());
        }
    }
 
    public static void main(String[] args) {
        MyRunnable1 r = new MyRunnable1();
        Thread t1 = new Thread(r,"thread1");
        Thread t2 = new Thread(r,"thread2");
        t1.start();
        t2.start();
    }
}

 

你可能感兴趣的:(threadLocal)