【无标题】

java多线程疑问

public class MainThread {
    private static boolean flag = true;

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            System.out.println("子线程启动了");
            while (flag){

            }
            System.out.println("flag变动了");
        }).start();
        System.out.println("主线程启动了");
        Thread.sleep(100);
        flag = false;
        Thread.sleep(100);
        System.out.println("主线程结束了");
    }
}
public class StopThread {
    private  static boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        long a = System.currentTimeMillis();
        Thread  backgroundThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (!stopRequested) {
 //                  StringBuilder stringBuilder = new StringBuilder("123"); //打印success
                   String s = new String("123"); //打印
//                    String s = new String(); //打印
//                    String s = "new String()"; //不打印
//                    System.out.println(1); //打印
//                    StringBuffer stringBuffer = new StringBuffer("123");//打印,因为有锁
//                    StringBuffer stringBuffer = new StringBuffer(); //不打印
                    //i++;
                }
                System.out.println("Success!");
            }
        });
        backgroundThread.start();
        TimeUnit.MILLISECONDS.sleep(500);
        stopRequested = true;
        System.out.println("用时 : " + (System.currentTimeMillis()-a));
    }
}

你可能感兴趣的:(java,jvm,servlet)