class MyThread extends Thread{ //创建Thread类的子类MyThread private String who; public MyThread(String str){ //构造方法,用于设置成员变量who who = str; } public void run(){ //覆盖Thread类的run()方法 for(int i=0;i<5;i++){ try { sleep((int)(1000*Math.random())); //sleep()方法必须写在try-catch块内 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(who+"正在运行!"); } } } public class App11_1 { public static void main(String[] args) { MyThread you = new MyThread("你"); MyThread she = new MyThread("她"); you.start(); she.start(); System.out.println("主方法main()运行结束!"); } }
主方法main()运行结束! 你正在运行! 她正在运行! 你正在运行! 你正在运行! 她正在运行! 她正在运行! 你正在运行! 她正在运行! 她正在运行! 你正在运行! Process finished with exit code 0