Java创建线程

一般来说,Java创建线程有三种方式:1.继承Thread类创建线程类,2.实现runnable接口创建线程类,3.使用callable和future创建线程。

继承Thread类:

需要重写其run()方法,run方法内的内容为执行体

调用start方法来启动线程

public class threadtest extends Thread 
{
	public void run()
	{
		for(int i=0;i<100;i++)
		{
			System.out.println(Thread.currentThread().getName()+" "+i);
		}
	}
	
	public static void main(String[] args)
	{
		threadtest t1=new threadtest();
		threadtest t2=new threadtest();
		
		System.out.println(Thread.currentThread().getName());//输出为main,表示当前线程是main()
		
		t1.start();
		t2.start();//两个线程交替执行
		
	}

}
实现Runnable接口

同样要实现run()方法

创建线程对象需要先创建runnable实现类实例,再将其实例作为Thread的target来创建Thread对象

public class threadtest implements Runnable 
{

	@Override
	public void run()
	{
			for(int i=0;i<100;i++)
			{
				System.out.println(Thread.currentThread().getName()+" "+i);
			}		
	}
	
	
	public static void main(String[] args)
	{
		threadtest t=new threadtest();
		new Thread(t,"线程1").start();
		new Thread(t,"线程2").start();//两个线程同样交替执行

		
	}

}

使用Callable和future

该接口可以看做是runnable的加强版,加强的特性如下:call()方法作为执行体,call方法可以有返回值,call方法可以声明抛出异常

但是callable对象不能直接作为Thread的target,作为Thread的target必须是FutureTask类

public class threadtest implements Callable<String>
{
	@Override
	public String call() throws Exception
	{
		String str=Thread.currentThread().getName();
		return str;
	}
	
	public static void main(String[] args) throws InterruptedException, ExecutionException
	{
			threadtest t=new threadtest();
			FutureTask<String> ts=new FutureTask<String>(t);
			
			new Thread(ts).start();
			
			while(!ts.isDone())
			{
				System.out.println(ts.get());//得到call方法的返回值
			}
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值