山哥 http://blog.csdn.net
我们通过同一个例子,看线程的两种创建方法,以及运行方法
一种是声明 Thread 的子类,重载 Thread 类的方法 run
public class MyThread extends Thread {
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');
}
}
}
运行时可以有两种方法,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。
// 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);
}
}
本文地址:http://com.8s8s.com/it/it15940.htm