When and how should I use a ThreadLocal variable?

前端 未结 25 2426
再見小時候
再見小時候 2020-11-22 12:35

When should I use a ThreadLocal variable?

How is it used?

25条回答
  •  忘掉有多难
    2020-11-22 13:20

    Try this small example, to get a feel for ThreadLocal variable:

    public class Book implements Runnable {
        private static final ThreadLocal> WORDS = ThreadLocal.withInitial(ArrayList::new);
    
        private final String bookName; // It is also the thread's name
        private final List words;
    
    
        public Book(String bookName, List words) {
            this.bookName = bookName;
            this.words = Collections.unmodifiableList(words);
        }
    
        public void run() {
            WORDS.get().addAll(words);
            System.out.printf("Result %s: '%s'.%n", bookName, String.join(", ", WORDS.get()));
        }
    
        public static void main(String[] args) {
            Thread t1 = new Thread(new Book("BookA", Arrays.asList("wordA1", "wordA2", "wordA3")));
            Thread t2 = new Thread(new Book("BookB", Arrays.asList("wordB1", "wordB2")));
            t1.start();
            t2.start();
        }
    }
    


    Console output, if thread BookA is done first:
    Result BookA: 'wordA1, wordA2, wordA3'.
    Result BookB: 'wordB1, wordB2'.

    Console output, if thread BookB is done first:
    Result BookB: 'wordB1, wordB2'.
    Result BookA: 'wordA1, wordA2, wordA3'.

提交回复
热议问题