Three ways to create multithreading and how to start multithreading


foreword

1. Three ways to create multithreading

1.1 Inherit the Thread class

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

1.2 Implement the Runnable interface

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

1.3 Implement the Callable interface

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

Second, the method of starting the thread

2.1 Inherit the Thread class thread start method

new MyThread1().start();

2.2 Implement the thread startup method of the Runnable interface

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

2.3 Implement the Callable interface thread startup method

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();
}

Guess you like

Origin blog.csdn.net/sunzixiao/article/details/130047301