/**
* @author yeyuting
* @create 2021/1/13
*/
public class Abc {
public static int i = 0;
public static void main(String[] args) throws InterruptedException {
List<Thread> list = new ArrayList<Thread>();
for(int i = 0; i < 10000; i ++) {
Thread thread = new Thread(new Nn());
thread.start();
list.add(thread);
}
for (Thread thread : list) {
thread.join();
}
System.out.println(i);
}
static class Nn implements Runnable{
public void run() {
synchronized ("锁"){
System.out.println(Thread.currentThread().getName()+"进行到第"+i+"个数");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
i ++;
}
}
}
}
synchronized用于线程的互斥访问,实现线程安全。
实现效果如下:
![]()