public class TestThread1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Runner1 r = new Runner1();
Thread t = new Thread(r);
t.start();
for(int i=0; i<10; i++) {
System.out.println("Main Thread :" + i);
}
}
}
class Runner1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<10; i++) {
System.out.println("Runner1 :" + i);
}
}
}
运行结果:(这里每个人运行的结果可能不一样,主要是让大家看到两个线程是互相交叉运行。在测试的时候可以在自己电脑上加大循环次数,效果更明显)
Main Thread :0
Runner1 :0
Runner1 :1
Main Thread :1
Runner1 :2
Main Thread :2
Runner1 :3
Runner1 :4
Runner1 :5
Runner1 :6
Runner1 :7
Runner1 :8
Runner1 :9
Main Thread :3
Main Thread :4
Main Thread :5
Main Thread :6
Main Thread :7
Main Thread :8
Main Thread :9
从上面运行结果可以看出,两个线程是交叉运行的。
Runner1 r = new Runner1();
Thread t = new Thread(r);
t.start();
实现了一个Runnable接口的类Runner1。new一个新的Thread.(Thread.为JAVA的线程类)
用t.start();方法运行线程。