使用ReentrantLock或者AtomicInteger实现此处的计数安全;
public class ThreadTest {
public ReentrantLock lock = new ReentrantLock();
// public AtomicInteger a = new AtomicInteger(0);
public static int a = 0;
public void test() {
try {
lock.lock();
a++;
} finally {
lock.unlock();
}
}
public static void test2() throws InterruptedException {
ThreadTest threadTest = new ThreadTest();
Vector<Thread> queue = new Vector<>();
for (int i = 0; i < 400; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 5; j++) {
threadTest.test();
System.out.println(Thread.currentThread().getName() + ":" + threadTest.a);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
queue.add(thread);
thread.start();
}
for (Thread t : queue) {
t.join();
}
System.out.println("size:"+queue.size());
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
test2();
System.out.println("耗时:" + (System.currentTimeMillis() - start));
}
}
使用线程池控制多线程安全:
线程池使用优点:
可以复用,减少线程创建销毁开销;
超过核心线程数任务会安排在队列里,不会因阻塞造成线程上下文频繁切换;
线程池集中管理;
public class ThreadLocalTest {
public static int a = 0;
//定义一个定长线程池
public static ExecutorService executorService = Executors.newScheduledThreadPool(10);
public static void main(String[] args) {
for (int i = 0; i < 200; i++) {
executorService.execute(() -> {
System.out.println(++a);
});
}
executorService.shutdown();
try {
executorService.awaitTermination(3, TimeUnit.MICROSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(a);
}
}
}