一、继承Thead类
1.继承Thread类重写run方法,通过Thread.start()方法启动线程,main方法里for循环和现场里面的for循环是一起执行的。
public class TestThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我会run方法"+i);
}
}
public static void main(String[] args) {
TestThread testThread = new TestThread();
testThread.start();
for (int i = 0; i < 200; i++) {
System.out.println("----->"+i);
}
}
}
二、实现runnable接口
- 实现runnable接口重写run方法,把实例对象放到Thread对象里,通过new Thread(raceImplent, “兔子”).start()方法启动线程。
public class RaceImplent implements Runnable {
private static String winner ;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子") && i==60 ){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (isOver(i)){
return;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
boolean isOver(int step){
if(winner != null){
return true;
}else if(step == 100){
winner = Thread.currentThread().getName();
System.out.println("冠军是:"+Thread.currentThread().getName());
}
return false;
}
public static void main(String[] args) {
RaceImplent raceImplent = new RaceImplent();
new Thread(raceImplent,"兔子").start();
new Thread(raceImplent,"乌龟").start();
}
}
三、实现callable接口
public class CallableTest implements Callable<List<String>> {
@Override
public List<String> call() throws Exception {
System.out.println(Thread.currentThread().getName());
ArrayList<String> objects = new ArrayList<>();
objects.add(Thread.currentThread().getName());
System.out.println("执行了....");
return objects;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableTest call1 = new CallableTest();
CallableTest call2 = new CallableTest();
/**创建线程池对象*/
ExecutorService service = Executors.newFixedThreadPool(2);
//可以执行Runnable对象或者Callable对象代表的线程
Future<List<String>> res1 = service.submit(call1);
Future<List<String>> res2 = service.submit(call2);
//get获取线程处理结果
List<String> list = res1.get();
System.out.println(list);
List<String> list2 = res2.get();
System.out.println(list2);
}
}
补充一下Future
Future是java 1.5引入的一个interface,可以方便的用于异步结果的获取
java8的CompletableFuture来实现异步调用, 使用allOf方法可以把异步执行的线程加到线程池里,待所有线程执行完毕才会执行后面逻辑。