Java可以有两种方法创建新的线程:
1、定义类实现Runnable接口
代码如下:
class Tasks implements Runnable {
public void run() {
int sum = 0;
for (int i = 0; i <= 100; i++) sum += i;
System.out.println("Result: " + sum);
}
}
public class JMain {
public static void main(String[] args) {
Thread t = new Thread(new Tasks());
t.start();
System.out.println("Waiting...");
}
}
2、定义一个线程类的子类然后重写其run方法
代码如下:
class myThread implements Thread {
public void run() {
int sum = 0;
for (int i = 0; i <= 100; i++) sum += i;
System.out.println("Result: " + sum);
}
}
public class JMain {
public static void main(String[] args) {
Thread t = new myThread();
t.start();
System.out.println("Waiting...");
}
}
注:使用Runnable接口可以为多个线程提供共享的数据。在实现Runnable接口的类的run方法中可以使用thread的静态方法,比如:public static Thread currentThread()获得当前线程的引用。