- 创建两个线程,创建方式可自选;
- 定义一个全局共享的 static int 变量 count,初始值为 0;
- 两个线程同时操作 count,每次操作 count 加 1;
- 每个线程做 100 次 count 的增加操作。
@SuppressWarnings("all")
public class DemoTest {
// 创建两个线程,创建方式可自选;
// 定义一个全局共享的 static int 变量 count,初始值为 0;
// 两个线程同时操作 count,每次操作 count 加 1;
// 每个线程做 100 次 count 的增加操作。
public static int count = 0;
public static Lock lock = new ReentrantLock();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
lock.lock();
count++;
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
lock.lock();
count++;
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
});
t1.start();
t2.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("总count= " + count);
}
}