线程安全——线程之间互不影响

package cn.itcast.day01.thread;

public class TestClient implements Runnable {
private SequenceNumber sn;

public TestClient(SequenceNumber sn) {
    super();
    this.sn = sn;
}


@Override
public void run() {
    for (int i = 0; i < 3; i++) {
        // 4.每个线程打出3个序列值
        System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + sn.getNextNum1() + "]");
    }
}

}


public class SequenceNumber {
//1:通过匿名内部类覆盖ThreadLocal的initialValu()方法,指定初始值
private static ThreadLocal seqNum = new ThreadLocal(){
public Integer initialValue() {
return 0;
}
};

// 2.获取下一个序列值
public int getNextNum1() {
    //每次取值增加1
    seqNum.set((Integer) seqNum.get() + 1);
    return (Integer) seqNum.get();
}

int i=0;

public int getNextNum2() {
    i+=1;
    return i;
}

public static void main(String[] args) {
    SequenceNumber sn = new SequenceNumber();
    //三个线程共享sn,各自产生序列号
    TestClient t1 = new TestClient(sn);
    TestClient t2 = new TestClient(sn);
    TestClient t3 = new TestClient(sn);
    new Thread(t1).start();
    new Thread(t2).start();
    new Thread(t3).start();
}

}

打印结果:

thread[Thread-1] sn[1]
thread[Thread-2] sn[1]
thread[Thread-1] sn[2]
thread[Thread-0] sn[2]
thread[Thread-1] sn[3]
thread[Thread-2] sn[2]
thread[Thread-0] sn[3]
thread[Thread-2] sn[3]

上一篇:关于Redis过期时间的细节


下一篇:杭电oj —— 2046(记忆化搜索)