到目前为止,我们仅用到两个线程:主线程和一个子线程。然而,你的程序可以创建所需的更多线程。例如,下面的程序创建了三个子线程:
1 // Create multiple threads. 2 class NewThread implements Runnable { 3 String name; // name of thread 4 Thread t; 5 NewThread(String threadname) { 6 name = threadname; 7 t = new Thread(this, name); 8 System.out.println("New thread: " + t); 9 t.start(); // Start the thread 10 } 11 12 // This is the entry point for thread. 13 public void run() { 14 try { 15 for(int i = 5; i > 0; i--) { 16 System.out.println(name + ": " + i); 17 Thread.sleep(1000); 18 } 19 } catch (InterruptedException e) { 20 System.out.println(name + "Interrupted"); 21 } 22 System.out.println(name + " exiting."); 23 } 24 } 25 26 class MultiThreadDemo { 27 public static void main(String args[]) { 28 new NewThread("One"); // start threads 29 new NewThread("Two"); 30 new NewThread("Three"); 31 try { 32 // wait for other threads to end 33 Thread.sleep(10000); 34 } catch (InterruptedException e) { 35 System.out.println("Main thread Interrupted"); 36 } 37 System.out.println("Main thread exiting."); 38 } 39 }
程序输出如下所示:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
如你所见,一旦启动,所有三个子线程共享CPU。注意main()中对sleep(10000)的调用。这使主线程沉睡十秒确保它最后结束。
系列文章: