package test;
//创建线程的第一种方式:继承java.lang.Thread类
//1.创建一个继承Thread的子类
class SubThread extends Thread {
//2.重写run()方法,方法内实现此子线程要完成的任务
public void run() {
for(int i = 0; i < 100; ++i) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
public class TestThread {
public static void main(String[] args) {
//3.创建一个子类的对象
SubThread st = new SubThread();
//4.调用线程的start()方法:启动此线程;并且调用相应的run()方法
//一个线程只能执行一次start();
//不能通过直接调用Thread实现类对象的run()方法去启动一个线程 st.run();//错误的,相当于主线程内启动的
st.start();
for(int i = 0; i < 100; ++i) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
package test;
//1.创建一个实现了Runnable接口的类
class SubThread1 implements Runnable{
//2.实现接口的抽象方法
public void run() {
//子线程执行的代码
for(int i = 0; i < 50; ++i) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
public class TestThread1 {
public static void main(String[] args) {
//3.创建一个Runnable接口实现类的对象
SubThread1 p = new SubThread1();
//要想启动多线程,必须调用start()
//4.将此方法作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程
Thread t1 = new Thread(p);
//5.调用start()方法,启动线程并执行run()
t1.start();
//再创建一个线程
Thread t2 = new Thread(p); //不用再重新创建p,直接传入Thread即可
t2.start();
}
}

原文:http://www.cnblogs.com/SkyeAngel/p/7811966.html