多线程的一个例子

    技术2022-05-11  140

    这个程序是照抄书上的例子,,《Java项目培训指南》,感觉还是很有收获,,,

    import java.lang.Thread;import java.lang.System;import java.lang.Math;import java.lang.InterruptedException;

    public  class Thread1 { public static void main(String args[]) throws java.io.IOException {  System.out.println("if want to show the result,press Return ");  MyThread thread1=new MyThread("thread1");  MyThread thread2=new MyThread("thread2");  thread1.start();  thread2.start();  char ch;  while ((ch=(char)System.in.read())!='/n');  thread1.tStart();  thread2.tStart();  while (thread1.isAlive()||thread2.isAlive())  {

      }  System.out.println("The thread test is end."); }}class MyThread extends Thread{ private boolean keepRunning=true; public MyThread(String id) {  super(id); } void randomWait() {  try  {   sleep((long)(3000*Math.random()));  }  catch(InterruptedException x)  {   System.out.println("Interrpted!!");  } } public void tStart() {  keepRunning=false; } public void run() {  int i=0;  while (keepRunning) i++;  for (int j=0;j<3;j++)  {   randomWait();   System.out.println("I am "+getName()+" - - I hava run "+i+" times.");   i++;  }  System.out.println(getName()+" is dead!"); }

    }


    最新回复(0)