public class Thh { /**
 * @param args
 */
public static void main(String[] args) {
 
 
Thh t=new Thh();
Inner in=t.new Inner();
for(int i=0;i<2;i++){
Thread tt=new Thread(in);
tt.start();
}
 
}
class Inner implements Runnable{
public void run(){
for(int i=0;i<100;i++){
System.out.println(i);
}
}
}}
我就是想演示一下多线程,我的目标是要用两个线程来同时打印输出public void run()里的语句,可是现在执行的效果是一个线程做一次循环,然后另外一个线程在做一次循环,不是两个线程同时执行run方法

解决方案 »

  1.   

    输出100个数一眨眼的功夫就完了所以看不到效果
    可以在run()方法里加上这句:Thread.sleep(100);
      

  2.   

    主要是时间片轮换间隔问题,没等轮到NEXT线程,100个数就打印完了!
      

  3.   

    Thh t=new Thh();for(int i=0;i<2;i++){
    Thread tt=new Thread(t.new Inner());
    tt.start();
    }
      

  4.   

    public class SimpleThreadDemo {
    // 启动线程的主方法
    public static void main(String[] args) {
    new SimpleThread1("线程1").start(); // 线程1启动
    new SimpleThread1("线程2").start(); // 线程2启动
    }
    }class SimpleThread1 extends Thread { public SimpleThread1(String str) {
    super(str); // 设置线程的标题
    } public void run() {
    for (int i = 0; i < 10; i++) {
    System.out.println(i + " " + getName());
    // 让程序暂时停止执行的时间,以便更清楚地观察线程相互执行
    try {
    sleep((long) (Math.random() * 1000));
    } catch (InterruptedException e) {
    }
    }
    System.out.println(getName() + "完成"); // 显示线程的完成信息
    }
    }