如题    并打印出来

解决方案 »

  1.   

    public class PrimeInThread
    {
    public static void main(String[] args)
    {
    for(int i = 0; i<10; i++)
    {
    new MyThread(i+"").start();
    }
    }
    };class MyThread extends Thread
    {
    public MyThread(String name)
    {
    super(name);
    }

    public void run()
    {
    String name = this.getName();
    int id = 0;
    try
    {
    id = Integer.parseInt(name);
    }
    catch(NumberFormatException e)
    {
    e.printStackTrace();
    } for(int i = (id*10+1); i<((id+1)*10+1); i++)
    {
    /*try
    {
    Thread.sleep(20);
    }
    catch(InterruptedException e)
    {
    e.printStackTrace();
    }*/

    boolean isPrime = true;

    if(i<2)
    continue;
    if(i==2)
    {
    System.out.println(i + " is a prmie");
    continue;
    }
    for(int j = 2; j<Math.sqrt(i)+1; j++)
    {
    if(i%j==0)
    {
    isPrime = false;
    break;
    }
    }
    if(isPrime)
    System.out.println(i + " is a prime.");
    }
    }
    };起了10个线程,每个负责10个数,不过计算素数实在太快了,输出结果看起来是顺序执行的,想看出是多线程的效果,就把注释掉的那段放回来。