1.实现Thread类是实现线程的创建 (两种)
2.实现Runnable接口的方式 (三种)
3.实现Callable接口的方式(一种)
1.实现Thread类是实现线程的创建线程 :
方式一:
static class MyThread extends Thread{
@Override
public void run() {
//线程执行任务
System.out.println("线程名称:"+Thread.currentThread().getName());
}
}
方式二:
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("线程名称:"+Thread.currentThread().getName());
}
};
thread.start();
继承Thread类的方式的缺点:java语言的设计当中只能实现单继承,如果继承了Thread类,就不能继承其他类。(不常用)
2.实现Runnable接口的方式 (Java不能实现多继承但可以实现多接口):
方式三:
static class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("线程名称:"+Thread.currentThread().getName());
}
}
public static void main(String[] args) {
//新建Runnable类
MyRunnable runnable = new MyRunnable();
//新建Thread类
Thread thread = new Thread(runnable);
//启动线程
thread.start();
}
方式四:
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程名称:"+Thread.currentThread().getName());
}
});
thread.start();
}
方式五:
public static void main(String[] args) {
Thread thread = new Thread(()->{
System.out.println("线程名称"+Thread.currentThread().getName());
});
thread.start();
}
3.实现Callable接口+Future容器的方式(创建并得到线程的执行结果)
方式六:
static class Mycallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int num =new Random().nextInt(10);
System.out.println("子线程名称:"+Thread.currentThread().getName()+",随机数"+num);
return num;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Mycallable mycallable = new Mycallable();
//创建一个FutureTask对象来接受返回值
FutureTask<Integer> futureTask = new FutureTask<>(mycallable);
Thread thread = new Thread(futureTask);
thread.start();
int result = futureTask.get();
System.out.println(String.format("线程名,%s,数字:%d",Thread.currentThread().getName(),result));
}