创建多线程有两种方式,一是直接使用Thread,二是使用Runnable实现静态代理
1,thread
public class Test extends Thread{
//复写run方法
public void run(){
}
}
//只能调用start。如果调run的话就是一个线程运行完之后再运行下一个线程
main{
Test test=new Test();
test.start();
}
2.Runnable静态代理:
实现Runnable接口重写run()
真实角色
代理角色+真实角色引用
public class Web12306 implements Runnable{
private int num=50;
@Override
public void run() {
while(true){
if(num<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
}
}
public static void main(String[] args) {
Web12306 web=new Web12306();
Thread t1=new Thread(web,"一号");
Thread t2=new Thread(web,"二号");
Thread t3=new Thread(web,"三号");
t1.start();
t2.start();
t3.start();
}
}
@Override
public void run() {
while(true){
if(num<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
}
}
public static void main(String[] args) {
Web12306 web=new Web12306();
Thread t1=new Thread(web,"一号");
Thread t2=new Thread(web,"二号");
Thread t3=new Thread(web,"三号");
t1.start();
t2.start();
t3.start();
}
}
两者推荐使用Runnable
避免单继承的局限性
便于资源共享