线程安全性问题

来源:互联网 发布:计算机算法书籍推荐 编辑:程序博客网 时间:2024/05/29 12:02
package com.nsn.sync;import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;public class SyncThread {private int value;public int getValue() {return value++;}public static void main(String[] args) {final SyncThread us = new SyncThread();List list = new ArrayList<>();Set set = new HashSet<>();for (int i = 0; i < 1000; i++) {Thread thread = new Thread("thread" + i) {@Overridepublic void run() {for (int i = 0; i < 100; i++) {int value = us.getValue();set.add(value);System.out.println(value + " " + super.getName());}}};list.add(thread);}for (Thread thread : list) {thread.start();}try {Thread.sleep(10000L);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(set.size());}}
0 0
原创粉丝点击