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

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

程序员文章站 2022-07-14 10:41:31
...

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]

相关标签: 线程安全