288 字
1 分钟
JUC-创建线程
JUC 笔记-创建线程
继承Thread类
package demo;
public class Demo1 {
public static void main(String[] args) { Demo1Thread demo1Thread = new Demo1Thread(); demo1Thread.start();
}}class Demo1Thread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); }}
不过这样还是有缺陷的,因为java是单继承,所以一个类一旦继承了Thread类,就没办法继承其它类了
实现Runnable接口
package demo;
public class Demo1 {
public static void main(String[] args) { new Thread(new Demo1Thread()).start();
}}class Demo1Thread implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); }}


Callable接口
前面的线程运行不会返回数据,Callable接口就是为了能接收会返回数据的线程的结果的。
package demo;
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;
public class Demo1 {
public static void main(String[] args) { Callable callable = new Demo1Thread(3,10); FutureTask<Integer> futureTask = new FutureTask(callable); Thread t = new Thread(futureTask); t.start(); try { Integer i = futureTask.get();
System.out.println("result: " + i); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); }
}}class Demo1Thread implements Callable<Integer> { private int a; private int b; public Demo1Thread(int a,int b) { this.a = a; this.b = b; }
public int getA() { return a; }
public int getB() { return b; }
public void setA(int a) { this.a = a; }
public void setB(int b) { this.b = b; }
@Override public Integer call() throws Exception { Thread.sleep(1000); return a + b; }
}
发现错误或想要改进这篇文章?
在 GitHub 上编辑此页 JUC-创建线程