📄 testthread2.java
字号:
package test.thread;
public class TestThread2 {
static int i = 200;
static Object lock = new Object();
public static void main(String[] args) {
Thread add = new AddThread();
Thread sub = new SubThread();
add.start();
sub.start();
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i = " + i);
}
}
class AddThread extends Thread{
public void run(){
for(int j=0; j<100; j++){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(TestThread2.lock){
TestThread2.i = TestThread2.i + 1;
}
System.out.println("add: " + TestThread2.i);
}
}
}
class SubThread extends Thread{
public void run(){
for(int j=0; j<100; j++){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(TestThread2.lock){
TestThread2.i = TestThread2.i - 1;
}
System.out.println("sub: " + TestThread2.i);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -