我们可以使用两种方法来创建线程。首先是通过扩展java.lang.Thread类,第二种方法是通过创建实现java.lang.Runnable接口的类。请参阅如何通过实现Runnable接口来创建线程?
在此示例中,我们将扩展Thread类。要在线程中运行代码,我们需要run()在类中提供方法。让我们看看下面的代码。
package org.nhooo.example.lang; public class NumberPrinter extends Thread { private String threadName; private int delay; public NumberPrinter(String threadName, int delay) { this.threadName = threadName; this.delay = delay; } // 启动线程时将调用run()方法。 @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread [" + threadName + "] = " + i); try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { NumberPrinter printerA = new NumberPrinter("A", 1000); NumberPrinter printerB = new NumberPrinter("B", 750); printerA.start(); printerB.start(); } }
我们的代码的示例结果是:
Thread [A] = 0 Thread [B] = 0 Thread [B] = 1 Thread [A] = 1 Thread [B] = 2 Thread [A] = 2 Thread [B] = 3 Thread [A] = 3 Thread [B] = 4 Thread [B] = 5 Thread [A] = 4 Thread [B] = 6 Thread [A] = 5 Thread [B] = 7 Thread [A] = 6 Thread [B] = 8 Thread [B] = 9 Thread [A] = 7 Thread [A] = 8 Thread [A] = 9