java Thread编程(一)如何创建线程

1,以继承Runnable接口的形式创建新的线程。 
package test;

public class HelloWorldRunnable implements Runnable{

	public static void main(String[] args) {
	
		HelloWorldRunnable helloWorld1 = new HelloWorldRunnable();
		HelloWorldRunnable helloWorld2 = new HelloWorldRunnable();
		HelloWorldRunnable helloWorld3 = new HelloWorldRunnable();
		Thread thread1 = new Thread(helloWorld1);
		Thread thread2 = new Thread(helloWorld2);
		Thread thread3 = new Thread(helloWorld2);
		
		thread1.start();
		System.out.println("============thread1====================");
		System.out.println("ID: "+thread1.getId());
		System.out.println("Name: "+thread1.getName());		
		
		thread2.start();
		System.out.println("============thread2====================");
		System.out.println("ID: "+thread2.getId());
		System.out.println("Name: "+thread2.getName());
		
		thread3.start();
		System.out.println("============thread3====================");
		System.out.println("ID: "+thread3.getId());
		System.out.println("Name: "+thread3.getName());
		
	}

	@Override
	public void run() {
		
		System.out.println("hello world!");
	}
	
}


输出为:

============thread1====================
ID: 8
Name: Thread-0
hello world!
============thread2====================
ID: 9
Name: Thread-1
============thread3====================
ID: 10
Name: Thread-2
hello world!
hello world!

稍微注意一下就会发现每次执行的结果都可能不同!

2,以继承Thread类的方式创建新的线程。

package test;

public class HelloWorldThread extends Thread{

	public static void main(String[] args) {
	
		HelloWorldThread thread1 = new HelloWorldThread();
		HelloWorldThread thread2 = new HelloWorldThread();
		HelloWorldThread thread3 = new HelloWorldThread();
		
		thread1.start();
		System.out.println("============thread1====================");
		System.out.println("ID: "+thread1.getId());
		System.out.println("Name: "+thread1.getName());
		
		thread2.start();
		System.out.println("============thread2====================");
		System.out.println("ID: "+thread2.getId());
		System.out.println("Name: "+thread2.getName());
		
		thread3.start();
		System.out.println("============thread3====================");
		System.out.println("ID: "+thread3.getId());
		System.out.println("Name: "+thread3.getName());
	}
	
	@Override
	public void run() {
		
		System.out.println("hello world!");
	}

}


输出的结果为:

============thread1====================
hello world!
ID: 8
Name: Thread-0
============thread2====================
ID: 9
Name: Thread-1
hello world!
============thread3====================
hello world!
ID: 10
Name: Thread-2

 

 

posted @ 2011-12-27 23:19  梦见舟  阅读(128)  评论(0编辑  收藏  举报