013.多线程-ThreadLocal

版权声明:本文为博主原创文章,允许转载,请标明出处。 https://blog.csdn.net/qwdafedv/article/details/84143859

为每一个线程提供一个局部变量。

code of demo:

  • 创建三个线程,分别打印递增的IDS

错误demo

package cn.qbz.thread;

/**
 * @Author: 花生米
 * @Date: 2018/11/16 18:15
 */
public class ThreadLocalTest {
    public static void main(String[] args) {
        //创建三个线程,每个线程均获得其IDS
        Ids ids = new Ids();
        GetIds t1 = new GetIds(ids);
        GetIds t2 = new GetIds(ids);
        GetIds t3 = new GetIds(ids);

        t1.start();
        t2.start();
        t3.start();
    }

}

class GetIds extends Thread {
    private Ids ids;

    public GetIds(Ids ids) {
        this.ids = ids;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(getName() + "..." + ids.nextId());
        }
    }
}

class Ids {
    private int id = 0;

    public int nextId() {
        return id++;
    }
}


通过创建多个被执行对象来解决

package cn.qbz.thread;

/**
 * @Author: 花生米
 * @Date: 2018/11/16 18:15
 */
public class ThreadLocalTest {
    public static void main(String[] args) {
        //创建三个线程,每个线程均获得其IDS
        Ids ids1 = new Ids();
        Ids ids2 = new Ids();
        Ids ids3 = new Ids();
        GetIds t1 = new GetIds(ids1);
        GetIds t2 = new GetIds(ids2);
        GetIds t3 = new GetIds(ids3);

        t1.start();
        t2.start();
        t3.start();
    }

}

class GetIds extends Thread {
    private Ids ids;

    public GetIds(Ids ids) {
        this.ids = ids;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(getName() + "..." + ids.nextId());
        }
    }
}

class Ids {
    private int id = 0;

    public int nextId() {
        return id++;
    }
}


使用Thread Local包装Ids

package cn.qbz.thread;

/**
 * @Author: 花生米
 * @Date: 2018/11/16 18:15
 */
public class ThreadLocalTest {
    public static void main(String[] args) {
        //创建三个线程,每个线程均获得其IDS
        Ids ids = new Ids();
        GetIds t1 = new GetIds(ids);
        GetIds t2 = new GetIds(ids);
        GetIds t3 = new GetIds(ids);

        t1.start();
        t2.start();
        t3.start();
    }

}

class GetIds extends Thread {
    private Ids ids;

    public GetIds(Ids ids) {
        this.ids = ids;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(getName() + "..." + ids.nextId());
        }
    }
}

class Ids {
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public int nextId() {
        threadLocal.set(threadLocal.get() + 1);
        return threadLocal.get();
    }
}

猜你喜欢

转载自blog.csdn.net/qwdafedv/article/details/84143859