5
回答
怎么让num线程安全,ThreadLocal怎么用
滴滴云服务器,限时包月0.9元,为开发者而生>>>   
public class UtilDemo {
	public static void main(String[] args) {
		Thread t = new Thread(new Th());
		Thread t1 = new Thread(new Th());
		Thread t2 = new Thread(new Th());
		
		t.start();
		t2.start();
		t1.start();
		try {
			t.sleep(500);
			t1.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}
class Th implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 10000; i++) {
			if(i%100 == 99){
				Demo.work();
			}
		}
	}
	
}

class Demo{
	static Integer num = 0;
	public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
	
	public static void work(){
		num +=1;
		threadLocal.set(num);
		
	}
	
}

 

举报
大溪
发帖于5个月前 5回/142阅

public class UtilDemo {
    public static void main(String[] args) {
        Thread t = new Thread(new Th());
        Thread t1 = new Thread(new Th());
        Thread t2 = new Thread(new Th());

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

class Th implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "==>" + Demo.work());
        }
    }

}

class Demo {
    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public static Integer work() {
        threadLocal.set(threadLocal.get() + 1);
        return threadLocal.get();
    }

}

 

结果输入

hread-2==>1
Thread-1==>1
Thread-0==>1
Thread-1==>2
Thread-2==>2
Thread-1==>3
Thread-0==>2
Thread-1==>4
Thread-2==>3
Thread-1==>5
Thread-0==>3
Thread-1==>6
Thread-2==>4
Thread-1==>7
Thread-0==>4
Thread-1==>8
Thread-2==>5
Thread-1==>9
Thread-0==>5
Thread-1==>10
Thread-2==>6
Thread-2==>7
Thread-2==>8
Thread-2==>9
Thread-2==>10
Thread-0==>6
Thread-0==>7
Thread-0==>8
Thread-0==>9
Thread-0==>10
 

酱紫 ? 楼主

顶部