阅读背景:

如何从服务器端发送退出时终止线程sendMsgToServer

来源:互联网 
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());}
    }
}
import java.io.BufferedReader;
import java.io.I



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: