多线程之竞争与锁

未完待续...

Posted by MatthewHan on 2020-01-14

示例

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
public class TestThread {

public static void main(String[] args) {
// new 出一个新的对象 t
ThreadFuck t1 = new ThreadFuck();
ThreadFuck t2 = new ThreadFuck();
// 两个线程
Thread thread1 = new Thread(t1, "Thread-1");
Thread thread2 = new Thread(t1, "Thread-2");
thread1.start();
thread2.start();
// t1.run();
}

}

class ThreadFuck implements Runnable {

int temp = 10;
// private Lock lock = new ReentrantLock();
@Override
public void run() {
// lock.lock();
for (int i = 0; i < 5; i++) {
temp -= 1;
try {
Thread.sleep(1);
} catch (InterruptedException ignored) {}
System.out.println(Thread.currentThread().getName() + "-temp = " + temp);
}
// lock.unlock();
}
}