在Java之中,实现多线程有两种途径: 继承Thread类 实现Runnable接口(Callable接口)
Thread类是一个支持多线程的功能类 格式: class 名称 extends Thread {} //多线程操作类 注意,在多线程的每个主体类之中,都要覆写Thread类中的run()方法 格式:public void fun() {} //没有返回值,线程一旦开始,就要一直执行,不能够返回内容 例:
class MyThread extends Thread { private String name; public MyThread (String name) { this.name = name ; } public void run() { for(int x=0 ; x < 200 ; x++ ) { System.out.println(this.name + "--->" + x); } } } public class Nice { public static void main(String args[]) { MyThread mt1 = new MyThread("A") ; MyThread mt2 = new MyThread("B") ; //mt1.run(); 其实这并不是多线程的执行,输出中没有实现多线程的特点 //mt2.run(); mt1.start(); //抢占资源,多线程的执行 mt2.start(); } }为什么启动多线程不用run(),用start()呢,因为start()方法不仅仅要启动多线程执行代码,还要根据不同的操作系统进行资源的分配
附:Thread常用方法
类别方法签名简介线程的创建Thread()线程的创建Thread(String name)线程的创建Thread(Runnable target)线程的创建Thread(Runnable target,String name)线程的方法void start()启动线程线程的方法static void sleep(long millis)线程休眠线程的方法static void sleep(long millis,int nanos)线程休眠线程的方法void join()使其他线程等待当前线程终止线程的方法void join(long millis)使其他线程等待当前线程终止线程的方法void join(long millis,int nanos)使其他线程等待当前线程终止线程的方法static void yield()当前运行线程释放处理器资源获取线程引用static Thread currentThread()返回当前运行的线程引用虽然Thread很好,但是它本身有一个缺陷,那就是他的继承问题,而接口不一样,Runnable接口就是为了解决单继承的限制 格式:
@FunctionalInterface public interface Runnable { public void run(); }
例:
class MyThread implements Runnable { private String name; public MyThread (String name) { this.name = name ; } public void run() { for(int x=0 ; x < 200 ; x++ ) { System.out.println(this.name + "--->" + x); } } } public class Nice { public static void main(String args[]) { MyThread mt1 = new MyThread("A") ; MyThread mt2 = new MyThread("B") ; //mt1.start(); //mt2.start(); } } //与继承Thread类相比,其实结构上没有什么区别,但是有一个地方不同 //继承Thread类,可以直接继承start方法 //但是,实现Runnable接口,就没有start方法啦引出:不管什么情况下,如果启动多线程一定要依靠Thread类完成! 构造方法:public Thread(Runnable target),接收的是Runnable接口对象
class MyThread implements Runnable { private String name; public MyThread (String name) { this.name = name ; } public void run() { for(int x=0 ; x < 200 ; x++ ) { System.out.println(this.name + "--->" + x); } } } public class Nice { public static void main(String args[]) { MyThread mt1 = new MyThread("A") ; MyThread mt2 = new MyThread("B") ; new Thread(mt1).start(); //实例化,使用了Thread类,为的是调用start()方法 new Thread(mt2).start(); } } //此时避免了单继承局限,实际应用中,Runnable接口是比较实用的