package com.test;
import java.util.Random;
public class ThreadTest3
{
/**
* @param args
*/
public static void main(String[] args)
{
for (int i = 0; i < 2; i++)
{
new Thread(){
@Override
public void run()
{
TestData testData = TestData.getInstance();
int data = new Random().nextInt();
testData.setData(data);
System.out.println(Thread.currentThread().getName()+" set Data:"+data);
System.out.println(Thread.currentThread().getName()+" get A Data:"+new A().get());
System.out.println(Thread.currentThread().getName()+" get B Data:"+new B().get());
}
}.start();
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class A{
public int get(){
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return TestData.getInstance().getData();
}
}
class B{
public int get(){
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return TestData.getInstance().getData();
}
}
class TestData{
private static ThreadLocal threadLocal = new ThreadLocal();
private int data;
public int getData(){
return data;
}
public void setData(int data){
this.data = data;
}
private TestData(){}
public static TestData getInstance(){
TestData testData = (TestData)threadLocal.get();
if(testData == null){
testData = new TestData();
threadLocal.set(testData);
}
return testData;
}
}
JAVA 多线程3 (线程内共享)
最新推荐文章于 2022-04-28 09:53:45 发布