您的位置:首页 > 编程语言 > Java开发

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

2011-12-27 23:19 423 查看
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

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thread 编程 java string class