您的位置:首页 > 其它

多线程的三种实现

2016-05-26 17:22 295 查看
1.继承Thread类,重写run方法

public class MyThread extends Thread{
//继承Thread会产生单继承局限,使用Runnable比较好

private String name;
MyThread(String name){
this.name = name;
}
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println(this.name+" "+i);
}
}
}


public static void main(String[] args) {
MyThread t1 = new MyThread("thread1");
MyThread t2 = new MyThread("thread2");
MyThread t3 = new MyThread("thread3");
t1.start();
/*
t1.start();
if (threadStatus != 0)//如果已經启动了,再次启动会抛这个异常
throw new IllegalThreadStateException();
*/
t2.start();
t3.start();

}


2.实现Runnable接口

public class MyThread implements Runnable{

private String name;
MyThread(String name){
this.name = name;
}
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println(this.name+" "+i);
}
}
}


public static void main(String[] args) {
MyThread t1 = new MyThread("thread");
//MyThread t2 = new MyThread("thread2");
//MyThread t3 = new MyThread("thread3");
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t1);
Thread thread3 = new Thread(t1);
thread1.start();
thread2.start();
thread3.start();

//        Runnable r = ()->{
//            for(int i=0;i<10;i++) {
//                System.out.println(i);
//            }};
//        Thread t1 = new Thread(r);
//        t1.setName("thread1");
//        Thread t2 = new Thread(r);
//        t2.setName("thread1");
//        Thread t3 = new Thread(r);
//        t3.setName("thread1");
//        t1.start();
//        t2.start();
//        t3.start();

}


3.实现Callable接口

public class MyCallable implements Callable{
//Callable接口比Runnable多了个返回值
//模拟卖票
int ticket = 10;
@Override
public String call() throws Exception {
while(ticket > 0) {
System.out.println("ticket has: "+ticket--);
}
return "ticket had sell done";
}

}


public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<String> cal = new MyCallable();
FutureTask<String> task = new FutureTask<String>(cal);
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
System.out.println(task.get());//取得返回值

//以下是Lambda表达式实现
/*
Callable<String> cal2 =()->{
for(int i=0;i<10;i++) {
System.out.println(i);
}
return "success";
};
FutureTask<String> task2 = new FutureTask<String>(cal2);
Thread thread11 = new Thread(task2);
Thread thread22 = new Thread(task2);
thread11.start();
thread22.start();
System.out.println(task2.get());//取得返回值
*/

}



Callable接口的源码

@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}


总结:继承Thread会产生单继承局限,使用Runnable比较好,Callable接口比runnable接口多了个返回值
但最终都是通过Thread类的start启动线程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: