多线程基础(四)-----ThreadLocal局部线程变量

在本文中,我们首先讲述了为什么要有局部线程变量,然后通过一系列的案例来演示局部线程变量ThreadLocal到底有什么作用。

 

ThreadLocal局部线程变量是什么?

ThreadLocal的实例代表了一个线程局部的变量,每条线程都只能看到自己的值,并不会影响到其它线程中也存在的该变量。

用于解决多线程并发访问出现的问题。

ThreadLocal让线程A与线程B的变量相互隔离,每个线程只能访问到自己的值。例如线程A的执行顺序为1-2-3,当线程A执行到2时,线程B 访问到线程A 的2,此时就会导致一系列的访问问题。所以ThreadLocal的使用时很有必要的。

如何去使用它?

实现以下功能

三个线程中的变量同时自增,打印输出结果。

package com.example.thread;

import java.util.Random;

import com.example.Demo;

public class RobotThread  implements Runnable{

	/**
	 * 线程的名称
	 */
	private String name;
	public RobotThread(String name)
	{
		this.name=name;
	}
	
	/**
	 * 线程局部变量
	 */
	 private static ThreadLocal<Integer> variable = new ThreadLocal<Integer>(){
	        @Override
	        protected Integer initialValue() {
	            return 0;
	        }        
	    };
	/**
	 * 线程启动    
	 */
	@Override
	public void run() {
       /**
        * 一共进行三个步骤A->B->C,分为不同的时刻执行
        */
        for(int i=1;i<=3;i++)
        {
        	Random r=new Random();
        	int time=r.nextInt(10);
        	try {
				Thread.sleep(time*200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        	variable.set(i);
        	System.out.println("当前的步骤:"+variable.get()+",当前的线程Id:"+Thread.currentThread().getId()+"当前线程的名称:"+name);		
        }
	}
	
	public static void main(String []args)
	{
		
		RobotThread rt1=new RobotThread("thread1");
		RobotThread rt2=new RobotThread("thread2");
		RobotThread rt3=new RobotThread("thread3");
        new Thread(rt1).start();
        new Thread(rt2).start();
        new Thread(rt3).start();

	}
	
	

}

当前的:1,当前的线程Id:11当前线程的名称:thread1
当前的:1,当前的线程Id:13当前线程的名称:thread3
当前的:1,当前的线程Id:12当前线程的名称:thread2
当前的:2,当前的线程Id:11当前线程的名称:thread1
当前的:2,当前的线程Id:13当前线程的名称:thread3
当前的:3,当前的线程Id:13当前线程的名称:thread3
当前的:2,当前的线程Id:12当前线程的名称:thread2
当前的:3,当前的线程Id:11当前线程的名称:thread1
当前的:3,当前的线程Id:12当前线程的名称:thread2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值