原文链接:http://blog.csdn.net/mustbehard/article/details/17175655
/*
* 创建线程时要继承Runnable接口
* 不要把宝贵的单继承机会占有掉
* 两种方式有点不用,实现Runnable
* 接口时多个线程中执行一个
* Runnable接口实现类时,run方法资源共享
* 而继承Thread时,run方法资源是
* 不能共享的!
*/
public class Test_Runnable_Thread {
public static void main(String[] args) {
/*
* 下面的代码执行400次打印语句
*/
SubThread subT1 = new SubThread();
SubThread subT2 = new SubThread();
SubThread subT3 = new SubThread();
SubThread subT4 = new SubThread();
subT1.start();
subT2.start();
subT3.start();
subT4.start();
/*
* 下面的代码执行100次打印语句
*/
SubRunnable subR = new SubRunnable();
Thread th1 = new Thread(subR);
Thread th2 = new Thread(subR);
Thread th3 = new Thread(subR);
Thread th4 = new Thread(subR);
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class SubRunnable implements Runnable {
private int id = 100;
@Override
public void run() {
while (true) { // 请自动关闭死循环,为了效果设置死循环 dos窗口中ctrl+c关闭
if (id > 0) {
System.out.println(Thread.currentThread().getName() + "run..."
+ id--);
}
}
}
}
class SubThread extends Thread {
private int id = 100;
@Override
public void run() {
while (true) { // 请自动关闭死循环,为了效果设置死循环 dos窗口中ctrl+c关闭
if (id > 0) {
System.out.println(Thread.currentThread().getName() + "run..."
+ id--);
}
}
}
}