【Java面试高频-多线程】- 如何创建多线程呢?创建多线程的方式有哪几种?

2021/5/13 12:27:21

本文主要是介绍【Java面试高频-多线程】- 如何创建多线程呢?创建多线程的方式有哪几种?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

如何创建多线程呢?创建多线程的方式有哪几种?

创建多线程的几种方式:

// 第一种继承Thread类的方式
	static class MyThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			System.out.println("Hello MyThread!");
		}
	}
	
	// 第二种实现runnable接口
	static class MyRun implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			System.out.println("Hello MyRun!");
		}
	}
	
	// 第三种实现callable方法
	static class MyCall implements Callable<String>{
		
		public String call() {
			// TODO Auto-generated method stub
			System.out.println("Helllo MyCall");
			return "success";
		}
	}

启动线程的几种方式

// 启动线程的5种方式
		new MyThread().start();
		
		new Thread(new MyRun()).start();
		
		new Thread(()-> {
			System.out.println("Hello Lambda!");
		}).start();
		
		
		Thread t = new Thread(new FutureTask<String>(new MyCall()));
		t.start();
		
		ExecutorService service = Executors.newCachedThreadPool();
		service.execute(()->{
			System.out.println("Hello ThreadPool");
		});
		service.shutdown();


这篇关于【Java面试高频-多线程】- 如何创建多线程呢?创建多线程的方式有哪几种?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程