编写一个程序,能够生成n个线程,每个线程每隔1秒打印自己的序号,当用户输入m后第m个线程结束.

解决方案 »

  1.   

    import java.util.Scanner;public class ThreadTest extends Thread 
    {
    private int index;
    private boolean go;

    public ThreadTest(int index)
    {
    super();
    this.index=index;
    go=true;
    } public int getIndex()
    {
    return index;
    } public void stopRun()
    {
    go=false;
    } public void run()
    {
    while(go)
    {
    System.out.println(index);
    try
    {
    sleep(1000);
    }catch(InterruptedException e){e.printStackTrace();};
    }
    } public static void main(String[] args) 
    {
    Scanner scanner= new Scanner(System.in);
    System.out.println("input N:");
    int n = scanner.nextInt(); if(n<=0)return; int m;
    ThreadTest[] threads=new ThreadTest[n]; for(int i=0 ; i<n ; i++)
    {
    threads[i]=new ThreadTest(i);
    threads[i].start();
    } while(true)
    {
    m = scanner.nextInt();
    if(m<0)
    {
    for(int i=0 ; i<n ; i++)
    {
    threads[i].stopRun();
    break;
    }
    }
    else if(m>=n)continue;
    threads[m].stopRun();
    }
    }
    }