/**
* 线程的创建:
* 通过继承Thread类来实现多线程
*
* 继承Thread类实现多线程的步骤:
* 在Java中负责实现线程功能的类是java.lang.Thread类
* 缺点:如果我们已经继承了一个类,则无法在继承Thread类
* 可以通过创建Thread类的实例来创建多线程
* 每个线程都是通过特定的Thread类的对象所对应的方法run()来完成其他操作的,方法run()称之为线程体
*/
public class TestThread extends Thread{
//run()方法是线程体
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName()+":"+i);
//getName()方法是返回线程的名称
}
}
public static void main(String[] args) {
TestThread t=new TestThread();//创建线程对象
t.start();//启动线程
TestThread t2=new TestThread();
t2.start();
}
}
/**
* 多线程的创建:
* 实现Runnable接口
*/
public class TestThread2 implements Runnable{
//run方法是线程体
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
public static void main(String[] args) {
//创建线程对象,把Runnable接口的对象作为参数传入
Thread t1=new Thread(new TestThread2());
t1.start();
Thread t2=new Thread(new TestThread2());
t2.start();
}
}