利用Thread 类以及Runnable接口创建线程
package javai; public class NewThread implements Runnable { Thread t; public NewThread() { t = new Thread(this, "I create a new thread."); System.out.println("Child thread: " + t); t.start(); } @Override public void run() { try { for (int i = 0; i < 5; i++) { System.out.println("Chinld thead: " + i); Thread.sleep(500); } } catch (Exception e) { System.out.println("Child thead sinterrupted "); } finally { System.out.println("Child thead exiting "); } } }
package javai; public class ThreadTest { public static void main(String[] args) { new NewThread(); try { for (int i = 0; i < 5; i++) { System.out.println("Main thead: " + i); Thread.sleep(500); } } catch (Exception e) { System.out.println("Main thead sinterrupted "); } finally { System.out.println("Main thead exiting "); } } }
运行结果:
Child thread: Thread[I create a new thread.,5,main]
Main thead: 0
Chinld thead: 0
Chinld thead: 1
Main thead: 1
Main thead: 2
Chinld thead: 2
Main thead: 3
Chinld thead: 3
Main thead: 4
Chinld thead: 4
Main thead exiting
Child thead exiting