用java编程设计四个线程,其中两个线程每次都对j加1,另两个线程每次对j减1,线程要用两种实现方式。

package study;

public class Factory {
    int j;

    Factory() {
        j = 0;
    }

    synchronized void add() {
        j++;
        System.out.println(Thread.currentThread().getName() + ":" + j);
    }

    synchronized void min() {
        j--;
        System.out.println(Thread.currentThread().getName() + ":" + j);
    }
}
package study;

public class T1 implements Runnable {

    Factory factory = null;
    
    T1(Factory factory) {
        this.factory = factory;
    }
    public int T1() {
        return 1;
    }
    
    @Override
    public void run() {
        while(true) {
            factory.add();
            try {
                Thread.sleep((int)Math.random() * 10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
package study;

public class T2 extends Thread {

    Factory factory = null;
    T2(Factory factory) {
        this.factory = factory;
    }
    @Override
    public void run() {
        while(true) {
            factory.min();
            try {
                Thread.sleep((int)Math.random() * 10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
package study;

public class Test2 {

    public static void main(String[] args) {
        Factory factory = new Factory();
        T1 t1 = new T1(factory);
        T2 t2 = new T2(factory);
        t2.setName("减线程1");
        
        T2 t3 = new T2(factory);
        t3.setName("减线程2");
        
        Thread thread1 = new Thread(t1, "加线程1");
        Thread thread2 = new Thread(t1, "加线程2");
        
        thread1.start();
        thread2.start();
        t2.start();
        t3.start();
    }
}

出处:https://www.cnblogs.com/duanxz/p/3332990.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值