下面的程序为什么不是以多线程的方式运行,它的运行结果是:先运行完100个“a”的打印,再完成100个“b”的打印,最后打印数字。为什么不是间隔打印呢?public class TestThread {
public static void main(String[] args) {
Runnable task1 = new PrintA('a', 100);
Runnable task2 = new PrintA('b', 100);
Runnable task3 = new PrintNumber(100); Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
Thread thread3 = new Thread(task3); thread1.start();
thread2.start();
thread3.start(); }
}class PrintA implements Runnable {
private char charToPrint; private int times; public PrintA(char c, int t) {
charToPrint = c;
times = t; } public void run() {
for (int i = 1; i <= times; i++) {
System.out.print(charToPrint);
}
}}class PrintNumber implements Runnable {
private int time; public PrintNumber(int n) {
time = n;
} public void run() {
for (int i = 1; i <= time; i++) {
System.out.print(" " + i);
}
}
}

解决方案 »

  1.   

    没有sleep分出机时让别的线程来得及处理。
      

  2.   

    跟怨气无关,确实是数量必须增加,必要时应该把线程数也增加。如果碰到机器性能好的话,这种东西是完全没感觉的,建议你这么修改:
            Thread[] tasks = new Thread[26];
            for (int i = 0; i < tasks.length; i++) {
                tasks[i] = new Thread(new PrintA((char)('a' + i), 1000));
            }
            for (int i = 0; i < tasks.length; i++) {
                tasks[i].start();
            }