多线程的的实现方式无非就是两种,一种是继承thread类,另一种是实现runable接口。
继承thread类
public class SynchornizeTest extends Thread{
private String name;
public SynchornizeTest(String name) {
super();
this.name = name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println(name+"第"+i+"次");
}
}
public static void main(String[] args) {
SynchornizeTest thread1 = new SynchornizeTest("张三");
SynchornizeTest thread2 = new SynchornizeTest("李四");
thread1.start();
thread2.start();
}
}
结果为:
实现runable
public class SynchornizeTest implements Runnable{
private String name;
public SynchornizeTest(String name) {
super();
this.name = name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"第"+i+"次");
}
}
public static void main(String[] args) {
SynchornizeTest thread1 = new SynchornizeTest("张三");
Thread t1=new Thread(thread1,"thread1");
SynchornizeTest thread2 = new SynchornizeTest("李四");
Thread t2=new Thread(thread2,"thread2");
t1.start();
t2.start();
}
}
结果:
从上述的两种不同的方式来看,都是通过run方法来实现的多线程,在我们实现runable接口来时,我们先要创建一个实现了runable的一个类对象,之后我们再创建一个线程并将对象传入。
(ps:这只是为了能够记住一下线程的实现方式的一个笔记)