这个类子类化Thread并且提供它自己的run()方法上面代码中的函数运行一个循环来打印传送过来的字符串到屏幕上然后等待一个随机的时间数目在循环十次后该函数打印DONE!然后退出并由它杀死这个线程下面是创建线程的主函数
public class TwoThreadsDemo {
public static void main (String[] args) {
new SimpleThread(Do it!)start();
new SimpleThread(Definitely not!)start();
}
}
注意该代码极为简单函数开始给定一个名字(它是该线程将要打印输出的字符串)并且调用start()然后start()将调用run()方法程序的结果如下所示
Do it!
Definitely not!
Definitely not!
Definitely not!
Do it!
Do it!
Do it!
Definitely not!
Do it!
Definitely not!
Do it!
Definitely not!
Do it!
Do it!
Definitely not!
Do it!
Definitely not!
Definitely not!
Do it!
DONE! Do it!
Definitely not!
DONE! Definitely not!
正如你所看到的这两个线程的输出结果纠合到一起在一个单线程程序中所有的Do it!命令将一起打印后面跟着输出Definitely not!
[] [] [] []