0
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicBoolean;
public class ThreadSandbox {
//static volatile boolean runLoopX = true;
static AtomicBoolean runLoopX = new AtomicBoolean();
public static void main(String[] args) {
final Thread thread1 = new Thread(new Runnable(){
@Override
public void run()
{
try {
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String userInputStr = "";
do {
System.out.println("Enter text for thread 1:");
userInputStr = userInput.readLine().trim();
System.out.println("User Input for thread 1: " + userInputStr);
} while (userInputStr.equals("e") == false && runLoopX.get()== false);
} catch (Exception e) {System.err.println(e.toString());}
runLoopX.set(true);
}
});
final Thread thread2 = new Thread(new Runnable(){
@Override
public void run()
{
try {
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String userInputStr = "";
do {
System.out.println("Enter text for thread 2:");
userInputStr = userInput.readLine().trim();
System.out.println("User Input for thread 2: " + userInputStr);
} while (userInputStr.equals("e") == false && runLoopX.get()== false);
} catch (Exception e) {System.err.println(e.toString());}
runLoopX.set(true);
}
});
Thread thread3 = new Thread(new Runnable(){
@Override
public void run()
{
do {
if (runLoopX.get() == true) {
thread1.interrupt();
thread2.interrupt();
}
} while (runLoopX.get() == false);
}
});
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
thread2.join();
thread3.join();
} catch (Exception e) {System.err.println(e.toString());}
}
}
问题: 如果我输入“E”的线程1输入,则线程1终止,但是线程2仍然在运行,如果我输入“E”为线程2输入,则thread2终止,但thread1仍在运行。如何终止线程sendMsgToServer时退出从服务器端发送
如何在两个线程中输入“e”时终止两个线程?
我实际上做这行,我想用一个套接字侦听传入的消息,另一个插座发送消息。所以当客户端或服务器输入e时,应用程序需要结束。 – shresthaal 2012-01-27 00:17:01
好吧,你所有的线程应该循环一个静态同步变量,比如'while(continueWork){}',并且这个变量所有的线程都可以设置并获取所有线程。 也需要设置超时为您的套接字。 我将编辑套接字的答案。 – daigoor 2012-01-30 14:55:14