1.8.3suspend与resume方法的缺点--不同步

 1 package com.cky.bean;
 2 
 3 /**
 4  * Created by edison on 2017/12/3.
 5  */
 6 public class MyObject {
 7     private String usrName = "1";
 8     private String pwd ="11";
 9     public void setValue(String u, String p) {
10         this.usrName = u;
11         if (Thread.currentThread().getName().equals("a")) {
12             System.out.println("停止a线程");
13             Thread.currentThread().suspend();
14         }
15         this.pwd =p;
16     }
17 
18     public void printNameAndPwd() {
19         System.out.println(usrName +":"+pwd);
20     }
21 }
 1 package com.cky.test;
 2 
 3 import com.cky.bean.MyObject;
 4 
 5 /**
 6  * Created by edison on 2017/12/3.
 7  */
 8 public class Run2 {
 9     public static void main(String[] args) {
10         try {
11             final MyObject myObject = new MyObject();
12             Thread th1=new Thread(){
13                 @Override
14                 public void run() {
15                     super.run();
16                     myObject.setValue("a", "aa");
17                 }
18             };
19             th1.setName("a");
20             th1.start();
21             Thread.sleep(500);
22             Thread th2=new Thread(){
23                 @Override
24                 public void run() {
25                     super.run();
26                     myObject.printNameAndPwd();
27                 }
28             };
29             th2.start();
30         } catch (InterruptedException e) {
31             e.printStackTrace();
32         }
33 
34 
35     }
36 }
C:itsoftjdkinjava -Didea.launcher.port=7538 "-Didea.launcher.bin.path=C:itsoftideaIntelliJ IDEA 2016.3.3in" -Dfile.encoding=UTF-8 -classpath "C:itsoftjdkjrelibcharsets.jar;C:itsoftjdkjrelibdeploy.jar;C:itsoftjdkjrelibextaccess-bridge-32.jar;C:itsoftjdkjrelibextcldrdata.jar;C:itsoftjdkjrelibextdnsns.jar;C:itsoftjdkjrelibextjaccess.jar;C:itsoftjdkjrelibextjfxrt.jar;C:itsoftjdkjrelibextlocaledata.jar;C:itsoftjdkjrelibext
ashorn.jar;C:itsoftjdkjrelibextsunec.jar;C:itsoftjdkjrelibextsunjce_provider.jar;C:itsoftjdkjrelibextsunmscapi.jar;C:itsoftjdkjrelibextsunpkcs11.jar;C:itsoftjdkjrelibextzipfs.jar;C:itsoftjdkjrelibjavaws.jar;C:itsoftjdkjrelibjce.jar;C:itsoftjdkjrelibjfr.jar;C:itsoftjdkjrelibjfxswt.jar;C:itsoftjdkjrelibjsse.jar;C:itsoftjdkjrelibmanagement-agent.jar;C:itsoftjdkjrelibplugin.jar;C:itsoftjdkjrelib
esources.jar;C:itsoftjdkjrelib
t.jar;C:多线程核心技术第一章outproduction第一章;C:itsoftideaIntelliJ IDEA 2016.3.3libidea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Run2
停止a线程
a:11

结果不同步,程序中使用suspend()得注意。

原文地址:https://www.cnblogs.com/edison20161121/p/7954786.html