简单学习使用Runnable匿名内部类实现线程的方法。
1.先看下直接使用Runnable实现线程的例子:
import java.util.Random;
class ThreadA implements Runnable {
public void run() {
System.out.println("num = " + new Random().nextInt(20));
}
}
public class runnable {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 2; i++) {
ThreadA th = new ThreadA();
new Thread(th).start();
}
}
}
2.转换成匿名内部类实现:
import java.util.Random;
public class runnable {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run(){
System.out.println("num = "+new Random().nextInt(20));
}
}).start();
}
}
}
两种方法结果是一样的。仔细体会