Java多线程实现的三种方式
1. 第一种继承Thread 类
package com.thread;
public class Mythread extends Thread {
private int ticket = 10;
@Override
public void run() {
for (int i = 0; i < 200; i++) {
if (ticket > 0) {
System.out.println("票数:" + this.ticket--);
}
}
}
}
2.第二种实现Runnable接口(推荐)
package com.thread;
public class MyThreadImp implements Runnable {
private int ticket = 10;
@Override
public void run() {
for (int i = 0; i < 200; i++) {
if (ticket > 0) {
System.out.println("票数:" + this.ticket--);
}
}
}
}
3.第三种实现Callable接口
package com.thread;
import java.util.concurrent.Callable;
/**
* 可以接收返回值
*
* @author 李保磊
*
*/
public class MyTreadCallable implements Callable<String> {
private int ticket = 10;
@Override
public String call() throws Exception {
for (int i = 0; i < 200; i++) {
if (ticket > 0) {
System.out.println("票数:" + this.ticket--);
}
}
return "票已卖完";
}
}
4.测试
package com.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* description:实现多线程的方法与区别
*
* @author 李保磊
*
*/
public class ThreadMain {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyTreadCallable mc1 = new MyTreadCallable();
MyTreadCallable mc2 = new MyTreadCallable();
FutureTask<String> task1 = new FutureTask<String>(mc1);
FutureTask<String> task2 = new FutureTask<String>(mc2);
new Thread(task1).start();
new Thread(task2).start();
System.out.println("A线程" + task1.get());
System.out.println("B线程" + task2.get());
}
}