简单的1,2,3,4线程先后执行方式示例

 1 package thread;
 2 
 3 /**
 4 * 线程的结合。
 5 * 当一个线程需要等待另一个线程结束时,叫做线程的结合。
 6 */
 7 public class JoinThread {
 8 /**    自定义线程类 */
 9 static class ThreadA extends Thread{
10 //线程的ID
11 private int ID = 0;
12 //线程运行时循环的次数
13 private int whileTimes = 0;
14 public ThreadA(int id, int times){
15 this.ID = id;
16 this.whileTimes = times;
17 }
18 public void run(){
19 System.out.println("ThreadA" + this.ID + " begin!");
20 int i=0; 
21 try {
22 //连续循环whileTimes次
23 while (i < this.whileTimes){
24 System.out.println("ThreadA-" + this.ID + ": " + i++);
25 //sleep方法将当前线程休眠。
26 Thread.sleep(200);
27 }
28 } catch (InterruptedException e) {
29 }
30 
31 System.out.println("ThreadA" + this.ID + " end!");
32 }
33 }
34 public static void main(String[] args) {
35 //新建4个线程对象
36 Thread thread1 = new ThreadA(1, 3);
37 Thread thread2 = new ThreadA(2, 2);
38 Thread thread3 = new ThreadA(3, 2);
39 Thread thread4 = new ThreadA(4, 4);
40 //启动所有线程
41 System.out.println("Main method begin. To start 4 threads!");
42 try {
43 thread1.start();
44 thread1.join();
45 thread2.start();
46 thread2.join();
47 thread3.start();
48 thread3.join();
49 thread4.start();
50 thread4.join();
51 } catch (InterruptedException e) {
52 // TODO: handle exception
53 }
54 
55 //等待所有线程运行结束
56 
57 //此时所有线程都运行结束
58 System.out.println("Main method end! All 4 threads are ended");
59 }
60 }

多线程没有控制的时候,线程的任务不一定被java虚拟机交替进行的

原文地址:https://www.cnblogs.com/chenxuezhouLearnProgram/p/5698350.html