线程和 BufferedReader
Thread and BufferedReader
当我想使用多线程作为键盘侦听器时遇到问题。
所以我写了这些代码。
private static boolean out=false;
public static void main(String[] args)
{
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
try{
reader.readLine();
reader.close();
}catch (Exception e){e.printStackTrace();}
out=true;
System.out.println(" have received the keyboard");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true)
if(out)
break;
System.out.println(" exit the loop");
}
}).start();
}
但是当我在console输入东西的时候,第二个Thread好像不能运行.
如果我的代码或表达不清楚或有误,请告诉我。
谢谢!
`
一旦您执行程序,第二个线程就已经 运行 但由于您尚未为变量 out
分配新值 if
-子句将始终并且无限计算为 false
,因此永远不会中断。
您可以通过将 true
分配给 out 并使其成为 volatile
来解决此问题,以便始终使用最新更新的值。尝试这样的事情:
private static volatile boolean out = false;
public static void main( String[] args )
{
new Thread( new Runnable()
{
@Override
public void run()
{
BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
try
{
reader.readLine();
// will only be executed after input since BufferedReader.readLine() is blocking.
out = true;
reader.close();
}
catch ( Exception e )
{
e.printStackTrace();
}
System.out.println( " have received the keyboard" );
}
} ).start();
new Thread( new Runnable()
{
@Override
public void run()
{
// added to show that the 2nd thread started.
System.out.println( "Thread 2 started running...." );
while ( true )
if ( out )
break;
System.out.println( " exit the loop" );
}
} ).start();
}
当我想使用多线程作为键盘侦听器时遇到问题。
所以我写了这些代码。
private static boolean out=false;
public static void main(String[] args)
{
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
try{
reader.readLine();
reader.close();
}catch (Exception e){e.printStackTrace();}
out=true;
System.out.println(" have received the keyboard");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true)
if(out)
break;
System.out.println(" exit the loop");
}
}).start();
}
但是当我在console输入东西的时候,第二个Thread好像不能运行.
如果我的代码或表达不清楚或有误,请告诉我。
谢谢! `
一旦您执行程序,第二个线程就已经 运行 但由于您尚未为变量 out
分配新值 if
-子句将始终并且无限计算为 false
,因此永远不会中断。
您可以通过将 true
分配给 out 并使其成为 volatile
来解决此问题,以便始终使用最新更新的值。尝试这样的事情:
private static volatile boolean out = false;
public static void main( String[] args )
{
new Thread( new Runnable()
{
@Override
public void run()
{
BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
try
{
reader.readLine();
// will only be executed after input since BufferedReader.readLine() is blocking.
out = true;
reader.close();
}
catch ( Exception e )
{
e.printStackTrace();
}
System.out.println( " have received the keyboard" );
}
} ).start();
new Thread( new Runnable()
{
@Override
public void run()
{
// added to show that the 2nd thread started.
System.out.println( "Thread 2 started running...." );
while ( true )
if ( out )
break;
System.out.println( " exit the loop" );
}
} ).start();
}