java多线程主要的实现方式
public class Test extends Thread{
@Override
public void run() {
System.out.println("执行了run方法");
for (int i = 0; i <10 ; i++) {
System.out.println(Thread.currentThread().getName()+"----------"+i);
try {
Thread.sleep(1000);//当前线程睡眠,让给其他线程运行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//方法一:继承Thread类,并创建这个对象,调用start方法
//所谓的线程可以看成是一条执行路径,一个时间点内只能运行一个线程,当一个线程睡眠,其他线程就会抢着执行
Test test = new Test();
Test test1 = new Test();
//开启一个线程要调用start方法,如果是调用run方法就不是格外开启一个线程了
test.start();//开启一个线程,让线程进入就绪状态
test1.start();// 开启另一个线程,让其进入就绪状态
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"============"+i);
}
}
}
public class Test implements Runnable{
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
System.out.println(Thread.currentThread().getName()+"-----"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
方法二:实现Runnable接口
Test test = new Test();//创建实现了runnable接口的对象
Thread thread = new Thread(test,"线程1");//创建Thread类,把实现了runnable接口的对象,传入新建的Thread类中,还可以修改Thread类的名字,使用的是有参构造方法实现
Thread thread2 = new Thread(test,"线程2");
thread.start();
thread2.start();
}
}
总结
- 实现Runnable接口,然后创建Thread,把实现了Runnable接口的类传入新建的Thread类中,建议使用实现Runnable接口的方法,因为java是单继承,需要把继承留给关键的类.
- 使用Runnable接口之后,不需要给静态变量加staic关键字,每次创建一个对象,作为共享对象即可,如果采用继承的方式,每创建一个线程都会有各自的变量,就需要加staiic关键字来约束成共享变量.
- 实现Runnable接口运用到了代理模式,Thread类中构造方法中声明了Runnable接口,用的时候只需要传入Runnable接口的实现类就行了,这里利用了多态;也就是说Thread和我自定义的类都实现了共同的接口,具有相同的功能,Thread是代理类,也就是代理人,自定义的类就是被代理人,我想实现线程的一些功能,我交给代理类Thread类去做好了,那些细节我不用去管,我只关心自己的具体的逻辑的实现,这也是一种面向对象思想的体现.