class MultiThreadDemo
{
    public static void main(String args[])
    {
        NamePrinter jacky = new NamePrinter("Jacky");
        NamePrinter mickel = new NamePrinter("Michel");
        NamePrinter jone = new NamePrinter("Jone");
        
        Thread thread1 = new Thread(jacky);
        Thread thread2 = new Thread(mickel);
        Thread thread3 = new Thread(jone);
        
        thread3.setPriority(Thread.MAX_PRIORITY);
        
        thread1.start();
        thread2.start();
        thread3.start();        
    }
}class NamePrinter implements Runnable
{
    private String name;
    
    public NamePrinter(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return name;
    }
    public synchronized void run()
    {
        int i=0;
        while(i<5)
        {  
            System.out.println("\n\ni = "+    i++      +"  name = "+name);
            System.out.println("ThreadName = "+Thread.currentThread().getName());  //这两行输出
                                                         //为什么一个线程不能完整输出
            try
            {
                Thread.sleep(2000);
            }catch(InterruptedException e)  
            {
                
            }
        }
    }
}输出:
i = 0  name = Jone
ThreadName = Thread-2
i = 0  name = Michel   //ThreadName =.....为什么没有输出???
i = 0  name = Jacky
ThreadName = Thread-0
ThreadName = Thread-1

解决方案 »

  1.   

    因为那个输出在后面啊!
     System.out.println("\n\ni = "+    i++      +"  name = "+name);运行完之后,应该打印第二部分,可是此时线程被打断,执行了别的线程,结果另一个线程先打印了, 所以。
      

  2.   


    public void run() {
            synchronized ("abc") {
                int i = 0;
                while (i < 5) {
                    System.out.println("\n\ni = " + i++ + "  name = " + name);
                    System.out.println("ThreadName = " + Thread.currentThread().getName());  //这两行输出
                    //为什么一个线程不能完整输出
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
      

  3.   

    把 try
                {
                    Thread.sleep(2000);
                }catch(InterruptedException e)  
                {
                    
                }去掉就可以了
      

  4.   

    弄了这么多天了,一个关键的问题还没明白:Thread是并发执行的,执行过程可能会交叉。
      

  5.   

    按4楼的说法,是不是单纯的
     public synchronized void run()
    是不能起到线程同步互斥的作用,一定要synchronized ("abc") 这种方式?
      

  6.   

    因为这是不同的对象,对方法加锁起不到lz需要的目的。
    而我写的synchronized ("abc")是把锁都加在“abc”这个对象上,3个线程执行到这的时候必须等待获得锁才能执行。
      

  7.   


    synchronized方法的锁是夹在 this 上面的 所以不同的对象的锁是不同的而同步代码块锁就是在后面的那个String上面
      

  8.   

    程序在我的机器上运行是没有问题的,一个线程一输出,没有楼主出现的问题,类似的情况我同学也遇到过,程序在她的机子上运行就有一个线程没有完全运行完毕就被打断,我想这个问题应该是cpu的时间片打不相同,当一个线程运行完一个时间片时就把cpu使用权交给另一个线程使用,而本身却没运行完一个周期