欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程范围内共享变量的概念与作用

程序员文章站 2024-02-09 17:57:46
...
/**
* ThreadScopeShareData.java
* cn.com.songjy.test.socket.thread
* Function: TODO
*
* version date author
* ──────────────────────────────────
* 1.0 2013-8-16 songjy
*
* Copyright (c) 2013, TNT All Rights Reserved.
*/

package cn.com.songjy.test.socket.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* ClassName:ThreadScopeShareData
* 线程范围内共享变量的概念与作用
* @author songjy
* @version 1.0
* @since v1.0
* @Date 2013-8-16 下午4:04:45
*/

public class ThreadScopeShareData {

private static Log log = LogFactory.getLog(ThreadScopeShareData.class);
private static Map<Thread, Integer> thread_data = new HashMap<Thread, Integer>();
private static int data;

public static void main(String[] args) {

for(int i=0; i<5; i++)
new Thread(new Runnable() {

@Override
public void run() {
data = new Random().nextInt();
int data = new Random().nextInt();
log.info(Thread.currentThread().getName() + " has put data :" + data);
thread_data.put(Thread.currentThread(), data);
new A().get();
new B().get();
}
}).start();
}

static class A {
public void get(){
int data = thread_data.get(Thread.currentThread());
log.info("A from " + Thread.currentThread().getName() + " get data :" + data);
}
}

static class B {
public void get(){
int data = thread_data.get(Thread.currentThread());
log.info("B from " + Thread.currentThread().getName() + " get data :" + data);
}
}
}



引自
[url]http://down.51cto.com/data/443412[/url]