package proj_decode;
public class TestSynchornized {
public static synchronized void add() {//类锁
long time = System.currentTimeMillis() / 1000;
System.out.println(Thread.currentThread().getName() + "_加法_" + time);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void devision() {
synchronized (TestSynchornized.class) {//类锁
long time = System.currentTimeMillis() / 1000;
System.out.println(Thread.currentThread().getName() + "_除法_" + time);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void plus() {
synchronized (TestSynchornized.this) {//对象锁
long time = System.currentTimeMillis() / 1000;
System.out.println(Thread.currentThread().getName() + "_减法_" + time);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void multiplication() {//对象锁
long time = System.currentTimeMillis() / 1000;
System.out.println(Thread.currentThread().getName() + "_乘法_" + time);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
final TestSynchornized t = new TestSynchornized();
Thread a1 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
t.plus();
}
}
};
Thread a2 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
t.multiplication();
}
}
};
Thread a3 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
TestSynchornized.add();
}
}
};
Thread a4 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
t.devision();
}
}
};
// a1.start();
// a2.start();
a3.start();
a4.start();
}
}
结果:
Thread-2_加法_1475985582
Thread-2_加法_1475985583
Thread-2_加法_1475985584
Thread-2_加法_1475985585
Thread-3_除法_1475985586
Thread-3_除法_1475985587
Thread-3_除法_1475985588
Thread-3_除法_1475985589
Thread-3_除法_1475985590
Thread-3_除法_1475985591
Thread-2_加法_1475985592
Thread-2_加法_1475985593
Thread-2_加法_1475985594
Thread-2_加法_1475985595
Thread-2_加法_1475985596
Thread-3_除法_1475985597
Thread-2_加法_1475985598
Thread-3_除法_1475985599
Thread-3_除法_1475985600
Thread-3_除法_1475985601