这个问题好奇怪呀,运行结果竟然是抛出NullPointerException
而且输出一次[Hello]

解决方案 »

  1.   

    你说的对,我在家里试就是你说的这个结果,
    但是我在单位就是:
    [Hello[Hello]
    ]
    我把c=new Call();这一句和Call c;放在一起,又是下面的结果:
    [Hello[Hello]
    ]
      

  2.   

    我这里运行正常呢 
    结果为
    [Hello[Hello]
    ]
      

  3.   

    [Hello[Hello]
    ]
    这个结果不正常啊,正常应该是:
    [Hello]
    [Hello]
      

  4.   

    t.start();

    try{
    Thread.sleep(10000);
    }
    catch(InterruptedException e){
    System.out.println("Thread is interrupted");
    }

    c=new Call();这样就会出错了,
    估计是线程启动后(t.start()),
    run()方法在c=new Call前调用c.callMe,此时c还没有实例化,所以出现空指针,
    如果c=new Call()在线程执行前(run方法启动前)运行就没有问题了。
      

  5.   

    1、
    class Caller implements Runnable{
    Call c;
    Thread t;
    public Caller(String str){
    t=new Thread(this,str);
    c=new Call();
    //t.start();

    }
    public void run(){
    c.CallMe();
    }
    }
    将t.start去掉,不在这里启动2、
    try{
    c1.t.start();
    c1.t.join();
    c2.t.start();
    c2.t.join();
    }
    catch(Exception e){
    System.out.println("Thread is interrupted");
    }试试吧。
      

  6.   

    我找到原因了,因为我的caller对象生成了两个call对象。我改成在主函数里生成一个call对象,把这个对象作为一个参数传给caller对象就对了,代码如下:
    public class TestSynchronization {
    public static void main(String[] args){
    Call c=new Call();
    Caller c1=new Caller(c,"Thread One");
    Caller c2=new Caller(c,"Thread Two");

    try{
    c1.t.join();
    c2.t.join();
    }
    catch(InterruptedException e){
    System.out.println("Thread is interrupted");
    }
    }
    }class Caller implements Runnable{
    Call c;
    Thread t;
    public Caller(Call c,String str){
    this.c=c;
    t=new Thread(this,str);
    t.start();
    //c=new Call();
    }
    public void run(){
    c.CallMe();
    //this.CallMe();
    }

    }class Call{
    synchronized void CallMe(){
    System.out.print("[Hello");
    try{
    Thread.sleep(1000);
    }
    catch(InterruptedException e){
    System.out.println("Thread is interrupted");
    }
    System.out.println("]");
    }
    }