public class ThreadDemo2 {
public static void main(String[] args) {
number n=new number();
Add a=new Add(n);
Delete d=new Delete(n);
Thread t1=new Thread(a);
Thread t2=new Thread(a);
Thread t3=new Thread(d);
Thread t4=new Thread(d);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class number
{
private int j=0;
public number(){}
public number(int j)
{
this.j=j;
}
public int getJ() {
return j;
}
public void setJ(int j) {
this.j = j;
}
}
class Add implements Runnable
{
private number n;
private int j;
public Add(number n)
{
this.n=n;
}
public void run()
{
while(true)
{
synchronized (this) {
j=n.getJ();
} System.out.println(Thread.currentThread().getName()+" ***"+j++);
}
}
}
class Delete implements Runnable
{
private number n;
private int j;
public Delete(number n)
{
this.n=n;
}
public void run()
{
while(true)
{
synchronized (this) {
j=n.getJ();
System.out.println(Thread.currentThread().getName()+" ***"+j--);
}
}
}
}
//自己写的代码但是没理想的效果,j++和j--怎么都一样?? |
|