java_lock锁

lock锁是一个接口,jdk5.0新增的接口:

在线程中创建一个他的实现类对象Reentrantlock,默认为fals可以改为true,改为true后是有序的

把操作共享资源的代码放入try中,在try下一行调用lock方法锁定,使用finally在里边使用unlock进行解锁

import java.util.concurrent.locks.ReentrantLock;

public class Test03 {
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        Thread thread1 = new Thread(threadTest);
        Thread thread2 = new Thread(threadTest);
        Thread thread3 = new Thread(threadTest);
        thread1.setName("窗口一");
        thread2.setName("窗口二");
        thread3.setName("窗口三");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class ThreadTest03 implements Runnable{

    private int ticket = 100;
    ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try{
                reentrantLock.lock();
                if(ticket>0) {
                    System.out.println(Thread.currentThread().getName()+ticket);
                    ticket--;
                }else{
                    break;
                }

            }finally{
                reentrantLock.unlock();
            }
        }

    }
}

 

上一篇:Java 创建多线程的两种方式 异步执行


下一篇:C通过JNI反向调用JAVA程序方法