Java synchronized与Lock对象锁

    xiaoxiao2021-03-25  115

    package test; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ThreadTest { private int j; private Lock lock=new ReentrantLock(); public static void main(String [] args){ ThreadTest tt=new ThreadTest(); for(int i=0;i<2;i++){ new Thread(tt.new Adder()).start(); new Thread(tt.new Subtractor()).start(); } } public class Subtractor implements Runnable { @Override public void run() { while(true){ synchronized (ThreadTest.this) { System.out.println("j--="+j--); } /*lock.lock(); try { System.out.println("j--="+j--); } finally { lock.unlock(); }*/ } } } private class Adder implements Runnable{ @Override public void run() { while(true){ synchronized (ThreadTest.this) { System.out.println("j++="+j++); } /*lock.lock(); try { System.out.println("j++="+j++); } finally { lock.unlock(); }*/ } } } }
    转载请注明原文地址: https://ju.6miu.com/read-19314.html

    最新回复(0)