以NetBeans环境为例,新建一个J2SE的项目,然后在项目中新建一个名为mythread的包,在mythread包中,新建两个类,分别为Main.java和MyThread.java,下面提供这两个文件的代码。
Main.java代码:
1 2 3 4 5 6 7 8 9 10 11 12 |
package mythread; /** * @author Jason */ public class Main { public static void main(String[] args) { for(int i = 0; i < 5; i++) new MyThread(i+1).start(); } } |
MyThread.java代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package mythread; /** * @author Jason */ public class MyThread extends Thread { int intCount = 1, intNumber; /** * 构造函数 * @param int num 线程编号 */ public MyThread(int num) { intNumber = num; System.out.println("创建线程 " + intNumber); } @Override /** * 线程启动 */ public void run() { while(true) { System.out.println("线程 " + intNumber + ":计数 " + intCount); if(++intCount == 9) return; } } } |