Skip to content

Commit 093ec27

Browse files
committed
添加多线程相关
1 parent f51831b commit 093ec27

File tree

5 files changed

+66
-0
lines changed

5 files changed

+66
-0
lines changed
Binary file not shown.
789 Bytes
Binary file not shown.
630 Bytes
Binary file not shown.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.duwei.multythread;
2+
3+
import java.util.concurrent.locks.ReentrantLock;
4+
/**
5+
* 有两个线程都对i进行++操作,为了保证线程安全,
6+
* 使用了 ReentrantLock,从用法上可以看出,
7+
* 与 synchronized相比, ReentrantLock就稍微复杂一点。
8+
* 因为必须在finally中进行解锁操作,如果不在 finally解锁,
9+
* 有可能代码出现异常锁没被释放,而synchronized是由JVM来释放锁。
10+
* @author 杜伟
11+
*
12+
*/
13+
public class ReentrantLockDemo implements Runnable{
14+
public static ReentrantLock lock = new ReentrantLock();
15+
public static int i = 0;
16+
@Override
17+
public void run(){
18+
for (int j = 0; j < 10000000; j++){
19+
lock.lock();
20+
try{
21+
i++;
22+
}
23+
finally{
24+
lock.unlock();
25+
}
26+
}
27+
}
28+
29+
public static void main(String[] args) throws InterruptedException{
30+
ReentrantLockDemo test = new ReentrantLockDemo();
31+
Thread t1 = new Thread(test);
32+
Thread t2 = new Thread(test);
33+
t1.start();
34+
t2.start();
35+
t1.join();
36+
t2.join();
37+
System.out.println(i);
38+
}
39+
40+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.duwei.multythread;
2+
/**
3+
* µ÷ÓÃThread.start&&Thread.runµÄÇø±ð£¡£¡£¡
4+
* @author ¶Åΰ
5+
*/
6+
public class ThreadDemo {
7+
8+
public static void main(String[] args) {
9+
// Thread thread = new Thread("t1"){
10+
// @Override
11+
// public void run(){
12+
// System.out.println(Thread.currentThread().getName());
13+
// }
14+
// };
15+
// thread.start();
16+
//----------------------------------------
17+
Thread thread = new Thread("t1"){
18+
@Override
19+
public void run(){
20+
System.out.println(Thread.currentThread().getName());
21+
}
22+
};
23+
thread.run();
24+
}
25+
26+
}

0 commit comments

Comments
 (0)