当前位置:首页 > 开发 > 编程语言 > 多线程 > 正文

threadLocal实例

发表于: 2013-05-20   作者:bijian1013   来源:转载   浏览:
摘要: 实例1: package com.bijian.thread; public class MyThread extends Thread { private static ThreadLocal tl = new ThreadLocal() { protected synchronized Object initialValue() { return new Inte

实例1

package com.bijian.thread;

public class MyThread extends Thread {

	private static ThreadLocal tl = new ThreadLocal() {
		protected synchronized Object initialValue() {
			return new Integer(sernum++);
		}
	};
	private static int sernum = 100;

	MyThread(String name) {
		super(name);
	}

	public void run() {
		for (int i = 0; i < 5; i++)
			System.out.println(getName() + " " + tl.get());
	}
}

 

package com.bijian.thread;

public class ThreadLocalDemo1 {

	public static void main(String[] args) {
		MyThread mt1 = new MyThread("A");
		MyThread mt2 = new MyThread("B");
		MyThread mt3 = new MyThread("C");
		mt1.start();
		mt2.start();
		mt3.start();
	}
}

 

运行结果:
C 101
A 100
B 102
A 100
C 101
A 100
B 102
A 100
C 101
A 100
B 102
C 101
B 102
C 101
B 102

 

实例2

package com.bijian.thread;

public class MyThread extends Thread {

	private static ThreadLocal tl = new ThreadLocal();
	private static int sernum = 100;

	MyThread(String name) {
		super(name);
	}

	public void run() {
		synchronized ("A") {
			tl.set("" + sernum++);
		}
		for (int i = 0; i < 10; i++)
			System.out.println(getName() + " " + tl.get());
	}
}

 

package com.bijian.thread;

public class ThreadLocalDemo2 {

	public static void main(String[] args) {
		MyThread mt1 = new MyThread("A");
		MyThread mt2 = new MyThread("B");
		MyThread mt3 = new MyThread("C");
		mt1.start();
		mt2.start();
		mt3.start();
	}
}

 

运行结果:
A 100
B 101
A 100
C 102
A 100
B 101
A 100
C 102
A 100
B 101
C 102
B 101
C 102
B 101
C 102

 

threadLocal实例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号