创建多线程的三种方法以及多线程怎么启动的


前言

一、创建多线程的三种方法

1.1 继承Thread类

class MyThread1 extends Thread{
    
    
	@Override
	public void run(){
    
    
		System.out.println("继承Thread类");
	}
}

1.2 实现Runnable接口

class MyThread2 implements Runnable{
    
    
	@Override
	public void run(){
    
    
		System.out.println("实现Runnable接口");
	}
}

1.3 实现Callable接口

class MyThread3 implements Callable<Integer>{
    
    
	@Override
	public Integer call() throws Exception{
    
    
		System.out.println("实现Callable接口");
		return 100;
	}
}

二、启动线程的方法

2.1 继承Thread类线程启动方法

new MyThread1().start();

2.2 实现Runnable接口线程启动方法

new Thread(new MyThread2()).start();

2.3 实现Callable接口线程启动方法

FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try{
    
    
	Integer i = futureTask.get();
}catch(InterruptException e){
    
    
	e.printStackTrace();
}catch(ExecutionException e){
    
    
	e.printStackTrace();
}

猜你喜欢

转载自blog.csdn.net/sunzixiao/article/details/130047301
今日推荐