Java ThreadLocal, javathreadlocal

Source: Internet
Author: User

Java ThreadLocal, javathreadlocal

ThreadLocal class represents a local variable of a thread. By placing data in ThreadLocal, each thread can create a copy of the variable. It can also be seen as another way of thread synchronization. By creating a local copy of the Variable Thread for each thread, this avoids conflicts when concurrent threads read and write the same variable resource at the same time.

Example:

import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import com.sun.javafx.webkit.Accessor;public class ThreadLocalTest {    static class ThreadLocalVariableHolder {        private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {            private Random random = new Random();                        protected synchronized Integer initialValue() {                return random.nextInt(10000);            }        };                public static void increment() {            value.set(value.get() + 1);        }                public static int get() {            return value.get();        }    }        static class Accessor implements Runnable{        private final int id;                public Accessor(int id) {            this.id = id;        }                @Override        public void run() {            while (!Thread.currentThread().isInterrupted()) {                ThreadLocalVariableHolder.increment();                System.out.println(this);                Thread.yield();            }        }                @Override        public String toString() {            return "#" + id + ": " + ThreadLocalVariableHolder.get();        }            }        public static void main(String[] args) {        ExecutorService executorService = Executors.newCachedThreadPool();        for (int i = 0; i < 5; i++) {            executorService.execute(new Accessor(i));        }        try {            TimeUnit.MICROSECONDS.sleep(1);        } catch (InterruptedException e) {            e.printStackTrace();        }        executorService.shutdownNow();    }}

Running result:

#1: 9685#1: 9686#2: 138#2: 139#2: 140#2: 141#0: 5255。。。

According to the running results, each thread is used for its own Local variables and Its read/write operations do not interfere with each other.

ThreadLocal provides three methods to operate, set, get, and remove.

  • In Android, ThreadLocal is used to create independent logoff objects for each thread.
public final class Looper {    private static final String TAG = "Looper";    // sThreadLocal.get() will return null unless you've called prepare().    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();    private static void prepare(boolean quitAllowed) {        if (sThreadLocal.get() != null) {            throw new RuntimeException("Only one Looper may be created per thread");        }        sThreadLocal.set(new Looper(quitAllowed));    }        。。。}

When a thread needs its own logoff and message queue, it calls logoff. prepare (), which creates the logoff object and MessageQueue of the thread and saves the logoff object in ThreadLocal.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.