目录
  1. 1. 示例
多线程之竞争与锁

示例

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();
}
}
文章作者: MatthewHan
文章链接: https://Matthew-Han.github.io/post/24ffa600-367c-11ea-ba8c-fb7580846ffa/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Espada
打赏
  • 打赏宁 🐴 呢!给 👴 爬!

评论