sy08_1:Thread子类的方法实现多线程

Thread子类的方法实现多线程

编写 TwoThreadsTest.java 程序文件,源代码如下:

class SimpleThread extends Thread {
     public SimpleThread(String str) {
         super(str);
     }
     public void run() {
         for (int i = 0; i < 10; i++) {
             System.out.println(i + " " + getName());
             try {
                 sleep((int)(Math.random() * 1000));
             } catch (InterruptedException e) {}
         }
         System.out.println("DONE! " + getName());
     }
 }
public class TwoThreadsTest {
     public static void main (String[] args) {
         new SimpleThread("Go to Beijing??").start();
         new SimpleThread("Stay here!!").start();
      }
     }

运行结果:

0 Go to Beijing??
0 Stay here!!
1 Go to Beijing??
1 Stay here!!
2 Go to Beijing??
2 Stay here!!
3 Stay here!!
4 Stay here!!
3 Go to Beijing??
4 Go to Beijing??
5 Go to Beijing??
5 Stay here!!
6 Go to Beijing??
6 Stay here!!
7 Stay here!!
8 Stay here!!
7 Go to Beijing??
8 Go to Beijing??
9 Go to Beijing??
9 Stay here!!
DONE! Go to Beijing??
DONE! Stay here!!

猜你喜欢

转载自blog.csdn.net/qq_40956679/article/details/80989746