Java多线程运行3线程

时间:2016-03-21 12:06:57

标签: java multithreading



public class TaskThreadDemo {
  public static void main(String[] args) {
    // Create tasks
    Runnable printA = new PrintChar('a', 100);
    Runnable printB = new PrintChar('b', 100);
    Runnable print100 = new PrintNum(100);

    // Create threads
    Thread thread1 = new Thread(printA);
    Thread thread2 = new Thread(printB);
    Thread thread3 = new Thread(print100);

    // Start threads
    thread1.start();
    thread2.start();
    thread3.start();
  }
}

// The task for printing a specified character in specified times
class PrintChar implements Runnable {
  private char charToPrint; // The character to print
  private int times; // The times to repeat

  /** Construct a task with specified character and number of
   *  times to print the character
   */
  public PrintChar(char c, int t) {
    charToPrint = c;
    times = t;
  }

  /** Override the run() method to tell the system
   *  what the task to perform
   */
  public void run() {
    for (int i = 0; i < times; i++) {
      System.out.print(charToPrint);
    }
  }
}

// The task class for printing number from 1 to n for a given n
class PrintNum implements Runnable {
  private int lastNum;

  /** Construct a task for printing 1, 2, ... i */
  public PrintNum(int n) {
    lastNum = n;
  }

  /** Tell the thread how to run */
  public void run() {
    for (int i = 1; i <= lastNum; i++) {
      System.out.print(" " + i);
    }
  }
}
&#13;
&#13;
&#13;

这是以前的代码,当代码运行时,输出将是aaaaaa ..... bbbbbbbb ......... 1 2 3 4 5 ...... 100

如果我想改变输出如何:

1 2 abbbbaaaaaaaaabbbbbbbbbb 3 4 5 6 7 aaaaaabbbb 8 9 10 aaaaaaaaaaaabbbbbbbbbbaa 11 12 13 14 ........ bbaaaabbaaaa ...... 100

感谢。

0 个答案:

没有答案