java实现多线程的方法

20 篇文章 0 订阅

Java虚拟机允许应用程序并发的运行多个线程,在java中实现多线程的方法由以下三种:

1. 实现Runnable接口,并且实现该接口的run()方法。主要步骤如下

1.1 自定义类并且实现Runnable接口,实现run()方法。

1.2 创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。

1.3 调用Thread的start()方法。

举例说明

//自定义类并且实现Runnable接口,实现run()方法
class MyThread implements Runnable
{
	public void run()
	{
		System.out.print("Thread body");
	}
}

public class Test 
{

	public static void main(String[] args)
	{
		MyThread thread = new MyThread();
		//创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
		Thread t = new Thread(thread);
		//调用Thread的start()方法。
		t.start();

	}

}
2. 继承Thread类,重写run()方法。

Thread本质上是实现了Runnable接口的一个实例,代表一个线程的实例,并且启动线程的唯一方法为调用Thread类的start()方法。这种方法是通过自定义继承自Thread的自定类,并重写run()方法实现。举例如下:

//自定义类并继承自Thread类,实现run()方法
class MyThread extends Thread
{
	public void run()
	{
		System.out.print("Method two!");
	}
}

public class Test 
{

	public static void main(String[] args)
	{
		MyThread thread = new MyThread();
		thread.start();

	}

}
3. 实现Callable接口,重写call()方法。

首先比较Callable接口与Runnable接口的不同点:

(1)Callable可以在任务结束的时候返回一个值,Runnable无返回值;

(2)Callable中的call()方法可以抛出异常,而Runnable的run()方法不能抛出异常;

(3)运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。

此方法实现多线程举例:

 

import java.util.concurrent.*;
public class CallableAndFuture 
{
	//创建线程类
	public static class CallableTest implements Callable<String>
	{
		public String call() throws Exception
		{
			return "Ni Hao";
		}
		
	}
	public static void main(String[] args)
	{
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		//启动线程
		Future<String>future = threadPool.submit(new CallableTest());
		try
		{
			System.out.println("wating thread to finish!");
			System.out.println(future.get());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
	}

}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值