Questions about java when testing multi-threaded execution?
public class Cai implements Runnable {
@Override
public synchronized void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
}
}
public class Run {
@Test
public void test2() throws Exception {
Cai cai = new Cai();
Thread thread = new Thread(cai);
Thread thread2 = new Thread(cai);
Thread thread3 = new Thread(cai);
thread.setName("线程1");
thread2.setName("线程2");
thread3.setName("线程3");
thread.start();
thread2.start();
thread3.start();
}
}
When the test2 method is executed, why does it appear like: Thread 1 loops 0-99, Thread 2 loops 0-10 and then the program ends. Why is this?
Thread 2 is not executed completely. Thread 3 has not been executed until???
Add thread.join, the main thread will wait for this thread to complete execution
It works for me, it works every time