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

java基础---->java多线程的使用(七)

时间:2017-07-27 15:47:02      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:rgs   用法   tar   star   rom   void   name   --   over   

  这里学习一下java多线程中的关于ThreadLocal的用法。

 

ThreadLocal的简单实例

 一、ThreadLocal的简单使用

package com.linux.huhx.thread2;

import java.util.Random;

public class ThreadLocalerTest {
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
       for (int i = 0; i < 2;i++) {
           new Thread(new Runnable() {
               @Override
               public void run() {
                   int randomValue = new Random().nextInt(9999);
                   System.out.println(Thread.currentThread().getName() + ", value: " + randomValue);
                   threadLocal.set(randomValue);

                   new GetA().get();
                   new GetB().get();
               }
           }).start();
       }
    }

    private static class GetA {
        public void get() {
            int value = threadLocal.get();
            System.out.println("A from " + Thread.currentThread().getName() + ", get data " + value);
        }
    }

    private static class GetB {
        public void get() {
            int value = threadLocal.get();
            System.out.println("A from " + Thread.currentThread().getName() + ", get data " + value);
        }
    }
}

运行的结果如下:

Thread-1, value: 2667
Thread-0, value: 9611
A from Thread-0, get data 9611
A from Thread-1, get data 2667
A from Thread-0, get data 9611
A from Thread-1, get data 2667

 

友情链接

 

java基础---->java多线程的使用(七)

标签:rgs   用法   tar   star   rom   void   name   --   over   

原文地址:http://www.cnblogs.com/huhx/p/baseusejavathread7.html

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