欢迎使用CSDN-markdown编辑器

来源:互联网 发布:mac怎么显示桌面 编辑:程序博客网 时间:2024/05/16 14:54

//设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。

package Runable;import java.util.concurrent.CountDownLatch;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;class Method {    private int j;    Lock lock = new ReentrantLock();    // Lock lock = new ReentrantLock();//加法和减法锁共有的锁    public Method(int j) {        super();        this.j = j;    }    public int getJ() {        return j;    }    public void setJ(int j) {        this.j = j;    }    public void add() {        j++;    }    public void minus() {        j--;    }}class RunableAdd implements Runnable {    // 加法线程    Method method = null;    public RunableAdd(Method method) {        super();        this.method = method;    }    @Override    public void run() {        // TODO Auto-generated method stub        method.lock.lock();        try {            method.add();            System.out.println(Thread.currentThread().getName() + "  j== "                    + method.getJ());            try {                Thread.sleep(100);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        } finally {            method.lock.unlock();        }    }}class RunableMinus implements Runnable {    // 减法线程    Method method = null;    public RunableMinus(Method method) {        super();        this.method = method;    }    @Override    public void run() {        // TODO Auto-generated method stub        method.lock.lock();        try {            method.minus();            System.out.println(Thread.currentThread().getName() + "  j== "                    + method.getJ());            try {                Thread.sleep(100);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        } finally {            method.lock.unlock();        }    }}public class RunableDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        Method method = new Method(2);        RunableAdd radd = new RunableAdd(method);        RunableMinus rmin = new RunableMinus(method);        Thread t1 = new Thread(radd);        Thread t2 = new Thread(radd);        Thread t3 = new Thread(rmin);        Thread t4 = new Thread(rmin);        t1.setName("t1加线程");        t2.setName("t2加线程");        t3.setName("t3减线程");        t4.setName("t4减线程");        t1.start();        t2.start();        t3.start();        t4.start();    }}
0 0
原创粉丝点击