1 public class DemoClass4ThreadSafe {
2 public static void main(String[] args) {
3 //TODO 线程安全
4 User18 user18 = new User18();
5
6 Thread t1 = new Thread(()->{
7 user18.name = "lisi";
8 try {
9 Thread.sleep(1000);
10 } catch (InterruptedException e) {
11 throw new RuntimeException(e);
12 }
13 System.out.println("t1=" + user18.name);
14 });
15
16 Thread t2 = new Thread(()->{
17 user18.name = "wangwu";
18 try {
19 Thread.sleep(2000);
20 } catch (InterruptedException e) {
21 throw new RuntimeException(e);
22 }
23 System.out.println("t2=" + user18.name);
24 });
25
26 t1.start();
27 t2.start();
28 System.out.println("main 打印数据.");
29
30
31 /*
32 * 打印结果:
33 main 打印数据.
34 t1=wangwu
35 t2=wangwu
36 *
37 *如果这样写:
38 * t2.start();
39 * t1.start();
40 *
41 * 打印结果:
42 * main 打印数据.
43 * t1=lisi
44 * t2=lisi
45 * */
46 }
47
48 }
49
50 class User18{
51 public String name;
52 }