import java.util.HashMap;
import java.util.Map;
import java.util.Random;publicclassTestThreadMap{privatestatic HashMap<Thread, Integer> map =new HashMap<Thread, Integer>();publicstaticvoidmain(String[] args){//TestThreadMap testThreadMap = new TestThreadMap();for(int i =0; i <2; i++){newThread(newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stubint data =newRandom().nextInt();
map.put(Thread.currentThread(), data);newA().Get();newB().Get();}}){}.start();}}staticclassA{publicvoidGet(){int data = map.get(Thread.currentThread());
System.out.println("A from "+ Thread.currentThread().getName()+" get data "+ data);}}staticclassB{publicvoidGet(){int data = map.get(Thread.currentThread());
System.out.println("B from "+ Thread.currentThread().getName()+" get data "+ data);}}}
ThreadLocal类似HashMap存储线程
import java.util.HashMap;
import java.util.Map;
import java.util.Random;publicclassTestThreadMap{privatestatic HashMap<Thread, Integer> map =new HashMap<Thread, Integer>();publicstaticvoidmain(String[] args){//TestThreadMap testThreadMap = new TestThreadMap();for(int i =0; i <2; i++){newThread(newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stubint data =newRandom().nextInt();
map.put(Thread.currentThread(), data);newA().Get();newB().Get();}}){}.start();}}staticclassA{publicvoidGet(){int data = map.get(Thread.currentThread());
System.out.println("A from "+ Thread.currentThread().getName()+" get data "+ data);}}staticclassB{publicvoidGet(){int data = map.get(Thread.currentThread());
System.out.println("B from "+ Thread.currentThread().getName()+" get data "+ data);}}}
import java.util.Random;publicclassTestThreadlocal_2{publicstaticvoidmain(String[] args){// TODO Auto-generated method stubfor(int i =0; i <2; i++){newThread(newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stubint data =newRandom().nextInt();
MyData.getInstance().setName("myData"+ data);
MyData.getInstance().setAge(data);newA().Get();newB().Get();}}){}.start();}}staticclassA{publicvoidGet(){
MyData data = MyData.getInstance();
System.out.println("A from "+ Thread.currentThread().getName()+" get data "+ data.getName()+", "+ data.getAge());}}staticclassB{publicvoidGet(){
MyData data = MyData.getInstance();
System.out.println("B from "+ Thread.currentThread().getName()+" get data "+ data.getName()+", "+ data.getAge());}}}classMyData{
String name;int age;publicstatic/*synchronized*/ MyData getInstance(){
MyData instance = threadLocal.get();if(instance == null){//不存在就创建一个与本线程有关的实例对象
instance =newMyData();
threadLocal.set(instance);}return instance;}//private static MyData instance = null;privatestatic ThreadLocal<MyData> threadLocal =new ThreadLocal<MyData>();public String getName(){return name;}publicvoidsetName(String name){this.name = name;}publicintgetAge(){return age;}publicvoidsetAge(int age){this.age = age;}}
线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;publicclassTestThreadPool{publicstaticvoidmain(String[] args){//固定大小的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);//缓存线程池,当线程不够用时会自动增加,多了会自动减少//ExecutorService threadPool = Executors.newCachedThreadPool();//单一线程池,线程死了可以重新启动//ExecutorService threadPool = Executors.newSingleThreadExecutor();for(int i =1; i <=10; i++){
final int taskid = i;
threadPool.execute(newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stubfor(int j =1; j <=10; j++){
System.out.println(Thread.currentThread().getName()+" is loop of "+ j +" for task of "+ taskid);}}});}
System.out.println("all have finished");
threadPool.shutdown();//线程池里没有任务了,线程池才关闭,等10个任务都完成后才关闭//threadPool.shutdownNow(); //一个线程完成之后立马关闭,此时只完成了3个任务/*//定时器线程池
Executors.newScheduledThreadPool(3).schedule(
new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("booming");
}
},
6,
TimeUnit.SECONDS); //多长时间后执行任务
*/
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(//以固定频率执行任务newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stub
System.out.println("booming");}},6,//初始时间2,//间隔时间
TimeUnit.SECONDS);}}
锁Lock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.xml.stream.events.StartDocument;publicclassTestLock{publicstaticvoidmain(String[] args){// TODO Auto-generated method stub
TestLock test =newTestLock();
test.init();}voidinit(){
final Outputer outputer =newOutputer();newThread(newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stubwhile(true){try{
Thread.sleep(10);}catch(Exception e){// TODO: handle exception
e.printStackTrace();}
outputer.Output("wangyuyuyuyuyuyuyuyu");}}}){}.start();newThread(newRunnable(){
@Override
publicvoidrun(){// TODO Auto-generated method stubwhile(true){try{
Thread.sleep(10);}catch(Exception e){// TODO: handle exception
e.printStackTrace();}
outputer.Output("zhouzhanzhaozhaozhaozhao");}}}){}.start();}classOutputer{
Lock lock =newReentrantLock();//锁publicvoidOutput(String name){int len = name.length();
lock.lock();try{for(int i =0; i < len; i++){
System.out.print(name.charAt(i));}
System.out.println("");} finally{// TODO: handle exception
lock.unlock();}}}}