Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

创建线程的3种方式

$
0
0

Thread:继承Thread类,可以直接使用this关键字,不能继承其他类;

runnable:可以继承其他类,多个线程共享一个target,必须使用Thread.currentThread().getName()获取当前线程名称,推荐使用这种;

callable:跟runnable差不多,不过他可以有返回值跟抛出异常;


继承Thread类

package com.jspjs.test.thread;

public class CreateByThread extends Thread {
	
	private int i;
	
	public void run(){
		for(;i<10;i++){
			System.out.println(getName()+"|"+i);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		for(int i =0;i<1000;i++){
			System.out.println(i);
			if(i==10){
				new CreateByThread().start();
				new CreateByThread().start();
			}
		}
		
	}
	

}

实现Runnable接口

package com.jspjs.test.thread;

public class CreateByRunnable implements Runnable {
	
	private int i;
	@Override
	public void run() {
		for(;i<10;i++){
			System.out.println(Thread.currentThread().getName()+"|"+i);
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CreateByRunnable runnable=new CreateByRunnable();
		new Thread(runnable,"子线程1").start();
		new Thread(runnable,"子线程2").start();
		
	}

}

实现Callable接口

package com.jspjs.test.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CreateByCallable implements Callable<Integer> {
	
	@Override
	public Integer call() throws Exception {
		Integer i=0;
		for(;i<10;i++){
			System.out.println(Thread.currentThread().getName()+"|"+i);
		}
		return i;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CreateByCallable callable=new CreateByCallable();
		FutureTask<Integer> task=new FutureTask<Integer>(callable);
		new Thread(task,"线程1").start();
		
		try {
			System.out.println("子线程的返回值:"+task.get());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


作者:xiaocie3456 发表于2013-8-30 19:10:38 原文链接
阅读:49 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles