package com.given.thread.entity;
public class J {
private int j;
public synchronized int getJ(){
return j;
}
public synchronized void addJ(){
this.j++;
}
public synchronized void decJ(){
this.j--;
}
}
package com.given.thread.entity;
public class Add extends Thread{
private J j;
public Add(J j) {
super();
this.j = j;
}
public void run() {
for(int i=0;i<5;i++) {
j.addJ();
System.out.println(Thread.currentThread().getName()+"将j+1后,j="+j.getJ());
}
}
}
package com.given.thread.entity;
public class Dec extends Thread {
private J j;
public Dec(J j) {
super();
this.j = j;
}
@Override
public void run() {
for(int i=0;i<5;i++) {
j.decJ();;
System.out.println(Thread.currentThread().getName()+"将j-1后,j="+j.getJ());
}
}
}
package com.given.thread;
import com.given.thread.entity.Add;
import com.given.thread.entity.Dec;
import com.given.thread.entity.J;
public class Test {
public static void main(String[] args) throws InterruptedException {
J j=new J();
Add a1=new Add(j);
Add a2=new Add(j);
Dec d1=new Dec(j);
Dec d2=new Dec(j);
a1.setName("线程1");
a2.setName("线程2");
d1.setName("线程1");
d2.setName("线程2");
a1.start();
a1.join();
a2.start();
a2.join();
d1.start();
d1.join();
d2.start();
d2.join();
}
}
线程1将j+1后,j=1
线程1将j+1后,j=2
线程1将j+1后,j=3
线程1将j+1后,j=4
线程1将j+1后,j=5
线程2将j+1后,j=6
线程2将j+1后,j=7
线程2将j+1后,j=8
线程2将j+1后,j=9
线程2将j+1后,j=10
线程1将j-1后,j=9
线程1将j-1后,j=8
线程1将j-1后,j=7
线程1将j-1后,j=6
线程1将j-1后,j=5
线程2将j-1后,j=4
线程2将j-1后,j=3
线程2将j-1后,j=2
线程2将j-1后,j=1
线程2将j-1后,j=0