欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java创建线程,

来源: javaer 分享于  点击 9147 次 点评:257

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方法的返回值
			}
		
	}

}


相关文章

    暂无相关文章
相关栏目:

用户点评