日期:2014-05-20  浏览次数:20813 次

(线程问题)各位高手为什么这个程序能编译不能运行啊?
import   java.io.*;

class   StringRunnable   implements   Runnable
{
    public   static   String   str;
    public   StringRunnable()
    {
        System.out.println( "StringRunnable ");
    }

    public   void   run()
    {
try
{
            BufferedReader   in   =   new   BufferedReader(new   InputStreamReader(System.in));
            str   =   in.readLine();
            System.out.println(str);
        }
        catch   (IOException   e)
        {
    System.out.println(e.getMessage());
}
    }
}

public   class   StringThread   extends   Thread
{
    public   StringThread()
    {
        System.out.println( "StringThread ");
    }

    public   void   run()
    {
        System.out.println( "The   length   of   string   is:   "   +   StringRunnable.str.length());
    }

    public   static   void   main(String[]   args)
    {
        Thread   thread1   =   new   Thread(new   StringRunnable());
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        Thread   thread2   =   new   StringThread();
        thread2.start();
    }
}



------解决方案--------------------
在你的另一个帖子里回答了
StringRunnable.str没有初始化,还是null, thread2走到System.out.println("The length of string is: " + StringRunnable.str.length()); 
时会出异常

thread1的优先级高并不代表threa1不执行完thread2就不执行,多以当thread1执行到str = in.readLine(); 时,如果用户不能及时响应输入数据,thread1就会一直堵塞,等待用户输入,而此时thread2就有可能执行,这样thread2走到System.out.println("The length of string is: " + StringRunnable.str.length()); 时,由于StringRunnable.str还是null,就造成thread2异常终了了

如果要保证顺序执行,可以不用设优先级,用jion就可以了
Thread thread1 = new Thread(new StringRunnable()); 
//thread1.setPriority(Thread.MAX_PRIORITY); 
thread1.start(); 
thread1.jion(); //
Thread thread2 = new StringThread(); 
thread2.start();