刚接触多线程,自己看了一点书,想写点东西,但是理论联系实际还有点困难,不知道方法和我需要实现的目的之间的联系,希望通过代码样例快速找到其中联系。for(int i=0; i<100; i++){
    System.out.println(i+1);
}就是这段小程序,如何用5个线程实现。我的理解就是,有五个线程同时打印。

解决方案 »

  1.   

    public class Test extends Thread {  private final int num;  public Test(int num) {
        this.num = num;
      }  @Override
      public void run() {
        for (int i = 0; i < 100; i++) {
          System.out.println((i + 1) + " in thread " + num);
          try {
            // 为了突出效果
            sleep(10);
          } catch (InterruptedException e) {
          }
        }
      }  public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i++) {
          new Test(i).start();
        }
      }}
      

  2.   


    /**每个线程各从1打印到100
    */
    public class Main{
        public static void main(String[] args) throws Exception {
            class runn implements Runnable {            final String robj = "";            public void run() {
                    for (int i = 0; i < 100; i++) {
                        synchronized (robj) {
                            System.out.println("线程:" + Thread.currentThread() + ",i=" + (i + 1));
                            System.out.flush();
                        }
                        try {
                            Thread.sleep(0);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
            runn r = new runn();
            for (int i = 0; i < 5; i++) {
                new Thread(r).start();
            }
        }
    /**五线程加起来一共从1-100
    */
    class runn implements Runnable {    final String robj = "";
        static int i = 0;    public void run() {
            for (; i < 100;) {
                synchronized (robj) {
                    System.out.println("线程:" + Thread.currentThread() + ",i=" + (++i));
                    System.out.flush();
                }
                try {
                    Thread.sleep(0);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }public class Main {    public static void main(String[] args) throws Exception {        runn r = new runn();
            for (int i = 0; i < 5; i++) {
                new Thread(r).start();
            }
        }
      

  3.   

    将第二个的
    static int i = 0;
    改为int i = 0;
    就是第一个等价