Java-线程-创建线程的方法

public class ThreadMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		/**
		 * 创建thread的子类,复写其run方法
		 */
		Thread thread = new Thread(){
			@Override
			public void run() {
				while(true){
					try {
						System.out.println(Thread.currentThread().getName()+" this is my name,i am going to sleep");
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("Thread finish");
				}	
			}
		};
		thread.start();

		/**
		 * 实现Runnable,推荐方法
		 */
		Thread thread2 = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try{	
						System.out.println(Thread.currentThread().getName()+" this is my name,i am going to sleep");
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("Thread finish");
					}
			}
		});
		thread2.start();
	}
}

 

此处提供了两个创建线程的方法,推荐使用第二种方法,因为使用Runnalble更为灵活,符合面向对象。

posted on 2011-10-01 23:28  victorlinwen  阅读(228)  评论(0)    收藏  举报