大虾们,为什么这个程序不能运行(线程方面的)?如何修改啊?
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();
}
}
------解决方案--------------------thread1.setPriority(Thread.MAX_PRIORITY);
thread1优先级高,并不代表thread1不执行完thread2就不会被执行
当thread1走到这里
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
str = in.readLine();
等到用户输入的时候,如果用户没有及时输入或者没有输入完成,thread1就会堵塞在这里
这时候,如果thread2开始了,运行到
System.out.println("The length of string is: " + StringRunnable.str.length());
由于StringRunnable.str还是null,调用length()就会造成thread2异常终止
如果LZ想让线程顺序执行,可以不用设优先级,直接用join就可以了
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();
thread1.start();
thread1.jion();
thread2.start();
}