demo,换成long就会出现重复id
Topic source我测试还好呀。jdk1.8
package demo.thread;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
public class TestAtomic {
private static final AtomicLong atomicInteger = new AtomicLong(0);
public static void main(String[] args) {
Set<Long> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
Thread thread = new Thread() {
@Override
public void run() {
long id = getId();
set.add(id);
System.out.println(id);
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(set.size() == 30 ? "不重复" : "重复");
}
public static long getId() {
return atomicInteger.incrementAndGet();
}
}
为了严谨,换成了线程安全的set。
package demo.thread;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicLong;
public class TestAtomic {
private static final AtomicLong atomicInteger = new AtomicLong(0);
public static void main(String[] args) {
Set<Long> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 30; i++) {
Thread thread = new Thread() {
@Override
public void run() {
long id = getId();
set.add(id);
System.out.println(id);
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(set.size() == 30 ? "不重复" : "重复");
}
public static long getId() {
return atomicInteger.incrementAndGet();
}
}
你这块写的啥玩意儿
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
你这相当于看似多线程的单线程,每次for循环都等待当前新建线程执行结束再进入下一循环,多线程基础回炉重造吧
- 1
Loading...