Java入门使用Thread入门

Java中的线程实现是通过继承java.lang.Thread类然后实现run方法;或者通过实现Runnable接口,实现run方法,然后在实例化Thread时传入此Runnable实例作为参数。

 

如下代码片段 DownloadThread从Thread继承实现run方法下载一个Url:

package hello;

import java.io.IOException;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * DownloadThread 从Thread继承,实现run方法
 * @author yukaizhao
 *
 */
public class DownloadThread extends Thread {
	
	@Override
	public void run(){
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet("http://yukaizhao.javaeye.com/");
		try {
            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = client.execute(httpGet,responseHandler);
			System.out.println(responseBody);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

如下代码片段,实现Runnable,休眠随机毫秒数,然后输出一行文本

package hello;

import java.util.Random;

/**
 * 实现Runnable,实现run方法
 * @author yukaizhao
 *
 */
public class RunnableImpl implements Runnable {
	static int _number = 0;
	public void run(){
		Random random = new Random();
		int sleepMm=random.nextInt(200);
		try {
			Thread.sleep(sleepMm);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(String.format("I'm %1d thread",++_number));
	}
}

 

如下代码,在main函数中调用线程实现:

package hello;

public class HelloThread {
	public static void main(String[] args) throws InterruptedException{
		//声明Thread变量
		DownloadThread thread = new DownloadThread();
		//调用run执行方法
		thread.run();
		//join等待thread执行完毕的信号
		thread.join();
		
		//声明Runnable
		Runnable[] impls = new Runnable[5];
		//声明Runnable数量相同的线程
		Thread[] threads = new Thread[impls.length];
		for(int i=0;i<impls.length;i++){
			impls[i] = new RunnableImpl();
			//将Runnable的实例作为参数传递给Thread的构造函数
			threads[i] = new Thread(impls[i]);
			//启动线程
			threads[i].start();
		}
	}
}
 

你可能感兴趣的:(java)