Java实现线程的三种方法

这里简述一下Java中实现多线程的三种方法:

一、继承Thread类

 即继承Thread类后,自行完成run()方法,即可通过start()方法启动线程。

public class method1 extends Thread{
	public void run(){
		System.out.println("MyFirstWay!");
	}
}

主函数如下:

public class test1 {
	public static void main(String[] args) {
		method1 meth1 = new method1();
		method1 meth2 = new method1();
		meth1.start();
		meth2.start();
	}
}

运行结果如下:

二、实现Runable()接口

即当所写的类已经继承一个接口时,使用Runnable()接口,实例化Thread,再把写的类传入,使用start()方法启动线程。

public class method2 implements Runnable{

	@Override
	public void run() {
		System.out.println("MySecondMethod!");
	}
	
}

主函数及运行结果如下:

public class test2 {

	public static void main(String[] args) {
		method2 method2 = new method2();
		method2 method22 = new method2();
		Thread thread1 = new Thread(method22);
		Thread thread = new Thread(method2);
		thread1.start();
		thread.start();
	}

}

三、实现Callable()接口

可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。

public class method3 implements Callable<String>{

	@Override
	public String call() throws Exception {
		return "method3";
	}

}

主函数及运行结果如下:

public class test3 {
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<?> future = threadPool.submit(new method3());
		try {
			System.out.println(future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值