码迷,mamicode.com
首页 > 编程语言 > 详细

java 多线程(threadlocal)

时间:2015-06-11 14:28:04      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

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();
    }
}

 

java 多线程(threadlocal)

标签:

原文地址:http://www.cnblogs.com/Fredric-2013/p/4568937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!