先看代码:
private static int s=0;
public static void main(String[] args) throws InterruptedException {
for (int j=0;j<10;j++){
Thread thread = new Thread(()->{
for (int k=0;k<1000;k++){
s++;
}
},"thread-"+j);
thread.start();
}
Thread.sleep(3000);
System.out.println(s);
}
众所周知,这个程序输出结果肯定是小于等于1w的,那有几种方法可以使这个结果一定等于1w呢?
法一:使用join操作
只需要在 thread.start() 后面加上 thread.join(); 即可
private static int s=0;
public static void main(String[] args) throws InterruptedException {
for (int j=0;j<100;j++){
Thread thread = new Thread(()->{
for (int k=0;k<1000;k++){
s++;
}
},"thread-"+j);
thread.start();
// join可以阻塞主线程,所以必须等待该线程执行结束后才开启下一个线程
thread.join();
}
System.out.println(s);
}
法二:使用原子类AtomicInteger
private static AtomicInteger s = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
for (int j=0;j<100;j++){
Thread thread = new Thread(()->{
for (int k=0;k<1000;k++){
// getAndIncrement方法相当于 s++,incrementAndGet相当于 ++s
s.getAndIncrement();
}
},"thread-"+j);
thread.start();
}
//主线程睡一会等待其他线程执行结束
Thread.sleep(3000);
System.out.println(s);
}
持续更新中,欢迎留言~~~