Java多线程顺序执行以及ThreadLocal

/**
 * 
 */
package com.ldar.user;


import java.util.concurrent.atomic.AtomicInteger;


import org.junit.Test;


import net.sf.ehcache.search.aggregator.Count;


/**
 * @author 
 * @date 2016年3月3日 上午9:03:51
 * @desc 多线程顺序执行
 */
public class MultiThreadSequentialExecTest {

@Test
public void test(){
final LockT t= new LockT();

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
t.m1();
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
t.m2();
}
});
t2.start();
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
t.m3();
}
});
t3.start();
}

static class T {
volatile int target =1;//只能保证内存可见性,不能保证原子性
synchronized void m1(){
for(int i=0;i<3;i++){
while(target ==2 || target == 3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A"+i);
target = 2;
notifyAll();
}
}

synchronized void m2(){
for(int i=0;i<3;i++){
while(target ==1 || target == 3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B"+i);
target = 3;
notifyAll();
}
}

synchronized void m3(){
for(int i=0;i<3;i++){
while(target ==1 || target == 2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C"+i);
target = 1;
notifyAll();
}
}
}

static class LockT {
private final AtomicInteger atomic = new AtomicInteger(1);
//每个线程有独立的副本,防止变量共享
private final ThreadLocal<Integer> local = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 1;
}
};
synchronized void m1(){
for(int i=0;i<3;i++){
while(atomic.get() == 2 || atomic.get() == 3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A"+local.get());
local.set(local.get()+1);
atomic.incrementAndGet();
//该方法只能在同步方法或同步块内部调用。如果当前线程不是对象所得持有者
notifyAll();
}
}

synchronized void m2(){
for(int i=0;i<3;i++){
while(atomic.get() == 1 || atomic.get() == 3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B"+local.get());
local.set(local.get()+2);
atomic.incrementAndGet();
notifyAll();
}
}

synchronized void m3(){
for(int i=0;i<3;i++){
while(atomic.get() == 1 || atomic.get() == 2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C"+local.get());
local.set(local.get()+3);
atomic.set(1);
notifyAll();
}
}

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值