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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值