volatile static int flag=0;
//#region
public static void main(String[] args) throws Exception {
int num=100;
for (int i = 0; i < 100; i++) {
int finalI = i;
new Thread(()->{
while(true){
if(flag== finalI){
System.out.println(Thread.currentThread().getName()+": "+finalI);
flag++;
break;
}
}
},"t"+i).start();
}
}
//#endregion
}
直接通过循环不能按顺序是因为线程按顺序启动并不代表线程会按顺序执行,t1.start();t2.start;无法保证t1一定比t2先执行run方法。因此要通过一个线程共享volatile变量保证顺序
for (int i = 0; i < 100; i++) {
int finalI = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+": "+ finalI);
},"t"+i).start();
}
通过countdownlatch,原理同volatile,存在一个线程共享变量
static CountDownLatch cdl = new CountDownLatch(100);
//#region
public static void main(String[] args) throws Exception {
int num=100;
for (int i = 0; i < 100; i++) {
int finalI = i;
new Thread(()->{
while(true){
if(cdl.getCount()== 100-finalI){
System.out.println(Thread.currentThread().getName()+": "+finalI);
cdl.countDown();
break;
}
}
},"t"+i).start();
}
}
semaphore配合原子类控制输出数顺序但不能控制线程顺序
semaphore(1) 类似锁机制。
static AtomicInteger num = new AtomicInteger(100);
//#region
public static void main(String[] args) throws Exception {
Semaphore se = new Semaphore(1);
for (int i = 0; i < 100; i++) {
int finalI = i;
new Thread(()->{
boolean isAcquire = false;
try {
se.acquire();
isAcquire = true;
System.out.println(Thread.currentThread().getName()+": "+num.getAndIncrement());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
if(isAcquire){
se.release();}
}
},"t"+i).start();
}
}