首页 > 代码库 > java基础---->java多线程的使用(七)

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

  这里学习一下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 = http://www.mamicode.com/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 =http://www.mamicode.com/ threadLocal.get();            System.out.println("A from " + Thread.currentThread().getName() + ", get data " + value);        }    }    private static class GetB {        public void get() {            int value =http://www.mamicode.com/ threadLocal.get();            System.out.println("A from " + Thread.currentThread().getName() + ", get data " + value);        }    }}

运行的结果如下:

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

 

友情链接

 

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