欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

制作四个线程,共同操作同一个数字,其中2个线程,对该数字进行++操作另外两个线程对该数字进行--操作。

程序员文章站 2024-01-26 08:23:34
...

class Data{

    public int j = 0;

}
class Plus implements Runnable{
    private Data data;
    public Plus(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        while (true){
            synchronized (data){
                try{
                    Thread.sleep(400);
                    data.j++;
                    System.out.println(Thread.currentThread().getName()+":"+data.j);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }

    }
}
class Sub implements Runnable{
    private Data data;
    public Sub(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        while(true){
            synchronized (data){
                try{
                    Thread.sleep(400);
                    data.j--;
                    System.out.println(Thread.currentThread().getName()+":"+data.j);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class AppTest {
    public static void main(String[] args) {
        Data data = new Data();
        Plus plus = new Plus(data);
        Sub sub = new Sub(data);
        new Thread(plus,"加线程一").start();
        new Thread(plus,"加线程二").start();
        new Thread(sub,"减线程一").start();
        new Thread(sub,"减线程二").start();
    }
}