多线程——Runnable接口
以实现Runable接口的方式创建线程比继承Thread类有很大的优越性,因为类不能多重继承,即一个类只能继承一个类,那么如果该类已经继承了一个类,就不能实现多线程了,但是可以通过实现Runable接口的方式实现多线程。
1、Runnable实现多线程
package pers.zhb.runnable;
public class MyThread implements Runnable{
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+":正在执行!"+i);
}
}
}
package pers.zhb.runnable;
public class RunnableDemo {
public static void main(String[] args) {
MyThread mt=new MyThread();
Thread t2=new Thread(mt);//Thread类本质上也是实现了Runnable接口,但是Run方法是空的
t2.start();
for (int i = 0; i < 20; i++) {
System.out.println("主函数线程!"+i);
}
System.out.println("主函数执行结束了");
}
}
2、join()方法的使用
主线程在子线程运行结束后才开始运行。
package pers.zhb.runnable;
public class MyThread implements Runnable{
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+":正在执行!"+i);
}
}
}
package pers.zhb.runnable;
public class RunnableDemo {
public static void main(String[] args) throws InterruptedException {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt);
t1.start();
t1.join();
for (int i = 0; i < 20; i++) {
System.out.println("主函数线程!" + i);
}
System.out.println("主函数执行结束了");
}
}
转载于//www.cnblogs.com/zhai1997/p/11370201.html
还没有评论,来说两句吧...