实现Runnable创建线程
//1、自定义线程类实现Runnable接口
public class RunnableDemo implements Runnable {
//2、实现run()方法,编写线程执行体
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+i+"号正在运行...");
}
}
public static void main(String[] args){
//3、创建线程对象,调用start()方法启动对象
RunnableDemo runnableDemo = new RunnableDemo();
Thread thread1 = new Thread(runnableDemo, "线程1组");
Thread thread2 = new Thread(runnableDemo, "线程2组");
thread1.start();
thread2.start();
}
}
实现Callable创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
//1、自定义线程类实现Callable接口
public class CallableDemo implements Callable<String> {
//2、实现call()方法,编写线程执行体
@Override
public String call() throws Exception {
for (int i = 1; i <=20;i++){
System.out.println("线程"+i+"号开启了...");
}
return null;
}
public static void main(String[] args) {
//3、创建线程对象,调用start()方法启动对象
FutureTask<String> futureTask1 = new FutureTask<>(new CallableDemo());
Thread thread1 =new Thread(futureTask1);
FutureTask<String> futureTask2 = new FutureTask<>(new CallableDemo());
Thread thread2 =new Thread(futureTask2);
thread1.start();
thread2.start();
}
}
Runnable和Callable的区别:
1、实现Runnable要实现它的run方法,实现Callable要实现它的call方法。
2、run方法不可以抛出异常,call方法可以抛出异常。
3、run方法无返回值,call方法有返回值。