杨凯
2023-10-18 caf451f76ac30aa222230e0bc2d0d7cb9f420bdf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.consum.test;
 
/**
 * 测试多线程并发
 */
public class synchronizedCode implements Runnable {
 
    static synchronizedCode instance = new synchronizedCode();
    static int i = 0;
 
    static String key = "1";
 
    public static void main(String[] args) throws InterruptedException {
        for (int j=0;j<5;j++){
            Thread t1 = new Thread(instance);
            t1.start();
        }
 
        System.out.println("线程执行结束");
    }
 
    @Override
    public void run() {
 
        String myKey;
        if (key == "1"){
            myKey = "def";
            key = "2";
        } else {
            myKey = "abc";
            key="1";
        }
 
        System.out.println(Thread.currentThread().getName() + ":" + myKey);
 
        synchronized (myKey){
            System.out.println(Thread.currentThread().getName() + "开始运行");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("我叫"+ Thread.currentThread().getName()+"运行结束");
        }
    }
}