多线程实现:
一、继承Thread类
注意:继承的Thread类中本身就有sleep()和start()方法,可以直接调用。
public class Test04 extends Thread{
private String name;
public Test04(String name){
this.name = name;
}
public void run(){
for (int i = 0; i <5; i++) {
System.out.println(this.name +"运行:"+i);
try {
sleep(1000); //睡眠一秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test04 thread1 = new Test04("A");
Test04 thread2 = new Test04("B");
thread1.start();
thread2.start();
}
}
二、实现Runnbale接口
public class Thread2 implements Runnable {
private String name;
public Thread2(String name){
this.name = name;
}
@Override
public void run(){
for (int i = 0; i <5; i++) {
System.out.println(this.name +"运行:"+i);
try {
Thread.sleep(1000); //睡眠一秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread2 thread1 = new Thread2("A");
Thread2 thread2 = new Thread2("B");
new Thread(thread1).start();
new Thread(thread2).start();
// new Thread2("A").run();
// new Thread2("B").run();
}
}
注意:实现的Runnable接口中只有一个run()方法,因此sleep()和start()方法都需借助Thread类。
通过Thread类的有参构造实现
有待研究:为什么要通过start()方法去执行多线程,而不是直接调用run()方法呢?