Java通过java.lang.Thread类完成多线程。我们通过同一个例子,看线程的两种创建方法,以及运行方法
一种是声明 Thread
的子类,重载 Thread
类的方法 run
Extend java.lang.Thread and override the run method.
public class MyThread extends Thread {
public void run() {//因为缺省的run()方法什么都不做,你必须创建Thread子类并重载run()以完成有用的工作。
for (int count = 1, row = 1; row < 20; row++, count++) {
for (int i = 0; i < count; i++)
System.out.print('*');
System.out.print('/n');
}
}
}
运行时可以有两种方法,A,B.
public static void main(String[] args) {
MyThread mt = new MyThread();//A
mt.start();//A
Thread myThread = new Thread(new MyThread());//B
myThread.start();//B
for (int i = 0; i < 500; i++) {
System.out.println(i);
}
}
另一种途径是声明一个类,该类实现
Runnable
接口。然后再实现方法 run
。
Implement java.lang.Runnable and implement the run method.
// public class MyThread extends Thread {
public class MyThread implements Runnable {
public void run() {
for (int count = 1, row = 1; row < 20; row++, count++) {
for (int i = 0; i < count; i++)
System.out.print('*');
System.out.print('/n');
}
}
}
运行时只能有一种方法B.
public static void main(String[] args) {
// MyThread mt = new MyThread();
// mt.start();
Thread myThread = new Thread(new MyThread());
myThread.start();
for (int i = 0; i < 500; i++) {
System.out.println(i);
}
}