Java多线程
进程:线程是在进程基础上创建并使用的 更小的程序单元 启动速度比进程速度快许多
专门的线程主题类,必须实现特定的接口或者继承特定的父类
继承Thread类实现多线程
java.lang.Thread,只要一个类继承了此类就表示这个类可以实现多线程处理了,但是还需要覆写THread类中提供的一个run方法,这个属于主方法
package org.example; class MyThread extends Thread{//线程的主体类 private String title; public MyThread(String title){ this.title=title; } @Override public void run() {//线程的主体方法 for (int x=0;x<10;x++){ System.out.println(this.title+"运行,x="+x); } } }
run方法不能被直接调用,所以要想启动多线程必须使用start()方法完成 执行顺序不可控
只要定义了多线程,多线程启动只有一种方法:thread类中的start方法()
基于Runnable接口实现多线程
第二种多线程主体定义结构:实现java.lang.Runnable接口
public class ThreadDemo { public static void main(String args[]) { Thread threada =new Thread(new MyThread("线程a")); Thread threadb =new Thread(new MyThread("线程b")); Thread threadc =new Thread(new MyThread("线程c")); threada.start(); threadb.start(); threadc.start(); }}
这个时候只实现了Runnable接口对象,所以此时线程主题类上不再有单继承局限
对于多线程实现,优先考虑Runnable接口,并且永恒都是通过Thread类对象启动多线程
Thread与Runnable关系
Runnable是最方便的 因为其可以避免单继承的局限,同时也可以更好的进行功能的扩充。
多线程的设计中,使用代理设计模式的结构,用户自定义的线程主体只是负责核心功能的实现,其他全部交由Thread类来处理
在进行Thread启动多线程的时候调用的是start()方法,而后找到的run()方法,但通过Thread类的构造方法传递了一个 Runnable接口对象的时候,那么接口对象被Thread类中的target属性保存,在start()方法执行时会调用Thread类中的run方法,而这个run方法去调用Runnable接口子类被覆写过的run方法
多线程开发的本质是在于多个线程进行同一资源的抢占,那么thread主要描述的是进程,而资源的描述是通过runnable完成的
范例:利用卖票程序来实现多个线程的资源并发访问
package org.example; class MyThread implements Runnable{//线程的主体类 private int ticket=5; private String title; public MyThread(){ this.title=title; } @Override public void run() {//线程的主体方法 for (int x=0;x<100;x++){ if (this.ticket > 0) { System.out.println("卖票.ticket="+this.ticket--); } } } } public class ThreadDemo { public static void main(String args[]) { MyThread mt=new MyThread(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); }}
callable实现多线程
runnable接口有个缺点:当线程执行完毕之后,无法获得一个返回值。
范例:使用callable
package org.example; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; class MyThread implements Callable<String >{ @Override public String call() throws Exception { for(int x=0;x<10;x++){ System.out.println("********线程执行,x="+x); } return "线程执行完毕"; } } public class ThreadDemo { public static void main(String args[]) throws ExecutionException, InterruptedException { FutureTask<String > task=new FutureTask<>(new MyThread()); new Thread(task).start(); System.out.println("线程返回数据"+task.get()); }}
解释Runnable和Callable的区别
1、Runnable是在jdk1.0时候提出的多线程的实现接口,而Callable是在jdk1.5之后提出的
2、java.lang.Runnable接口之中提出一个run方法,没有返回值
3、java.util.concurrent.Callable接口提供有call()方法,可以有返回值