java锁样例

reentrantLock

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class reentrantLockTest {

    volatile private static int nextPrintWho = 1;
    private static  ReentrantLock lock = new ReentrantLock();

    final private static Condition conditionA = lock.newCondition();
//    final private static Condition conditionB = lock.newCondition();
//    final private static Condition conditionC = lock.newCondition();

    public static void main(String[] args){
        char c = 'C';

        Thread threadA = new Thread(){
            public void run(){
                try {
                    lock.lock();
                    int num = 1;
                    while(num<53){
                        while(nextPrintWho != 1){
                            conditionA.await();
                        }
                        System.out.println("ThreadA:"+num++);
                        System.out.println("ThreadA:"+num++);
                        nextPrintWho = 0;
                        conditionA.signalAll();
                    }

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        };


        Thread threadB = new Thread(){
            public void run(){
                try {
                    lock.lock();

                    char ch = 'A';
                    while(ch<='Z'){
                        while(nextPrintWho != 0){
                            conditionA.await();
                        }
                        System.out.println("ThreadB:"+ch++);
                        nextPrintWho = 1;
                        conditionA.signalAll();
                    }

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        };

        Thread threadC = new Thread(){
            public void run(){
                try {
                    lock.lock();
                    while(nextPrintWho != 3){
                        conditionA.await();
                    }

                    for(int i=0;i<3;i++){
                        System.out.println("ThreadC:"+(i+1));
                    }
                    nextPrintWho = 1;
                    conditionA.signalAll();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        };


        Thread[] aArray = new Thread[5];
        Thread[] bArray = new Thread[5];
//        Thread[] cArray = new Thread[5];

        for(int i=0;i<1;i++){

            aArray[i] = new Thread(threadA);
            bArray[i] = new Thread(threadB);
//            cArray[i] = new Thread(threadC);

            aArray[i].start();
            bArray[i].start();
        }
    }
}

Semaphore

import java.util.concurrent.Semaphore;

/*
* 生产者消费者模型
 */
public class SemaphoreTest {
    private static final int N = 10;
    /**
     * full 产品容量
     * empty 空余容量
     * mutex 读写锁
     */
    private static Semaphore full,empty,mutex;
    //记录当前的产品数量
    private static volatile int count = 0;
    static {
        /**
         * full 初始化0个产品
         * empty 初始化有N个空余位置放置产品
         * mutex 初始化每次最多只有一个线程可以读写
         */
        full = new Semaphore(0);
        empty = new Semaphore(N);
        mutex = new Semaphore(1);
    }
    //生产者类
    static class Producer implements Runnable{

        @Override
        public void run() {
            while (true){
                try{
                    empty.acquire();//等待空位
                    mutex.acquire();//等待读写锁
                    count++;
                    System.out.println("生产者生产了一个,目前:"+count);
                    mutex.release();//释放读写锁
                    full.release();//放置产品
                    //随机休息一段时间,让生产者线程有机会抢占读写锁
                    Thread.sleep((int)Math.random()%10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //消费者类
    static class Consumer implements Runnable{

        @Override
        public void run() {
            while (true){
                try{
                    full.acquire();//等待产品
                    mutex.acquire();//等待读写锁
                    count--;
                    System.out.println("消费者消费了一个,目前:"+count);
                    mutex.release();//释放读写锁
                    empty.release();//放置产品
                    //随机休息一段时间,让生消费线程有机会抢占读写锁
                    Thread.sleep((int)Math.random()%10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args){
        new Thread(new Producer()).start();
        new Thread(new Consumer()).start();
    }
}

threadPool

/**
 * 使用线程池开辟新线程的步骤
 * 1.创建线程池对象
 * 2.创建Runnable实例
 * 3.提交Runable实例
 * 4.关闭线程池(选择)
 * public static ExecutorService newCachedThreadPool()
 * public static ExecutorService newFixedThreadPool(int nThreads)
 * public static ExecutorService newSingleThreadExecutor()
 */

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MyRunnable implements Runnable{
    @Override
    public void run() {

        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+"::"+i);
        }
    }
}

public class threadPool {

    public static void main(String[] args) {
        //创建线程池对象
        ExecutorService service = Executors.newFixedThreadPool(2);
        //执行Runnable对象代表的线程
        service.submit(new MyRunnable());
        service.submit(new MyRunnable());
        //关闭线程池
        service.shutdown();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值