多线程编程,(四种方式) 三线程依次输出ABC

package com.ahys;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ABC三个线程依次输出ABC
 */
public class ABC {

    public static void main(String[] args) throws Exception {
        //method1();
        //synMethod();
       // lockPark();
        //semaphore();
        lock();

    }


    /**
     * 错误代码
     * @throws Exception
     */
    public static void method1() throws Exception {
        AtomicInteger count = new AtomicInteger(0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while ((count.get()%3)==0){
                    System.out.println(Thread.currentThread().getName()+" : A");
                    count.addAndGet(1);

                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while ((count.get()%3)==1){
                    System.out.println(Thread.currentThread().getName()+" : B");
                    count.addAndGet(1);

                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while ((count.get()%3)==2){
                    System.out.println(Thread.currentThread().getName()+" : C");
                    count.addAndGet(1);
                }
            }
        }).start();


        System.in.read();

    }



    /**
     * syn 锁实现方式
     */
    public static void synMethod(){
        Object lock = new Object();
        new PrintThread("A",lock).start();
        new PrintThread("B",lock).start();
        new PrintThread("C",lock).start();

    }



    /*******************************************************************************************1***********************************************************/
    public static volatile Integer integer = new Integer(0);


    /**
     * 打印线程
     */
    public static class PrintThread extends Thread{

        private String print;

        private Object lock;


        public PrintThread(String print,Object lock){
            this.print = print;
            this.lock = lock;
            this.setName(print);
        }


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

        public   boolean condition(){
            if("A".equals(print)&&(integer % 3 == 0)){
                return true;
            }
            if("B".equals(print)&&(integer % 3 == 1)){
                return true;
            }
            if("C".equals(print)&&(integer % 3 == 2)){
                return true;
            }
            return false;
        }
        @Override
        public void run(){

            while(true){
                //抢到锁
                synchronized (lock){
                    if(condition()){
                        print();
                        integer ++;
                    }else {
                        try {
                            //当前线程挂起 让出资源
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                   // System.out.println(Thread.currentThread().getName()+" run over, integer "+integer);
                    //通知
                    //notifyAll()方法能够唤醒所有正在等待这个对象锁的线程;
                    //调用某个对象的notify()方法能够唤醒一个正在等待这个对象的锁的线程,如果有多个线程都在等待这个对象的锁,则只能唤醒其中一个线程
                    lock.notify();

                }
            }
        }
    }


    /*******************************************************************************************2***********************************************************/

    /**
     * 基于lockpark的方式实现
     */
    public static void lockPark(){

        PrintParkThread a =null ,b = null,c =null;
        c = new PrintParkThread("C",true);
        b = new PrintParkThread("B",true);
        a = new PrintParkThread("A",false);
        c.unpark = a;
        b.unpark = c;
        a.unpark = b;

        a.start();
        b.start();
        c.start();
        //LockSupport.park();
    }


    /**
     * park
     */
    public static class PrintParkThread extends Thread {

        public PrintParkThread(String print, boolean parkSelf){
            this.setName(print);
            this.print = print;
            this.parkSelf = parkSelf;
        }

        public String print;

        private boolean parkSelf;

        private Thread unpark;

        public void print(){
            System.out.println(Thread.currentThread().getName()+" park  : "+print);
        }


        @Override
        public void run(){
            System.out.println(Thread.currentThread().getName()+" park run start");
            if(parkSelf){
                //阻塞自己
                LockSupport.park(this);
                System.out.println(Thread.currentThread().getName()+"park  park ");
            }
            while(true){
                print();
                //放开下一个
                LockSupport.unpark(unpark);
                try {
                    Thread.sleep(new Random().nextInt(5000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LockSupport.park(this);

            }
        }
    }



    /*******************************************************************************************3***********************************************************/

    /**
     *基于信号量形式
     */

    public static void semaphore(){
        Semaphore as = new Semaphore(1),bs=new Semaphore(0),cs=new Semaphore(0);
        PrintSemaphoreThread c = new PrintSemaphoreThread("C",cs,as);
        PrintSemaphoreThread b = new PrintSemaphoreThread("B",bs,cs);
        PrintSemaphoreThread a = new PrintSemaphoreThread("A",as,bs);

        a.start();
        b.start();
        c.start();
    }


    /**
     * Semaphore
     */
    public static class PrintSemaphoreThread extends Thread {

        public PrintSemaphoreThread(String print, Semaphore acquire,Semaphore release){
            this.setName(print);
            this.print = print;
            this.acquire = acquire;
            this.release = release;
        }

        public String print;

        Semaphore acquire;

        Semaphore release;




        public void print(){
            System.out.println(Thread.currentThread().getName()+" Semaphore  : "+print);
        }


        @Override
        public void run(){
            System.out.println(Thread.currentThread().getName()+" Semaphore run start");
            while(true){
                try {
                    acquire.acquire();
                    print();
                    release.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }



    /*******************************************************************************************4***********************************************************/

    /**
     * lock 方式
     */

    public static void lock(){

        Lock lock = new ReentrantLock();
        Condition ac = lock.newCondition();
        Condition bc = lock.newCondition();
        Condition cc = lock.newCondition();
        PrintLockThread c = new PrintLockThread("C",lock,cc,ac);
        PrintLockThread b = new PrintLockThread("B",lock,bc,cc);
        PrintLockThread a = new PrintLockThread("A",lock,ac,bc);

        a.start();
        b.start();
        c.start();

    }

    public static class PrintLockThread extends Thread {

        public PrintLockThread(String print,  Lock lock,Condition await, Condition signalAll){
            this.setName(print);
            this.print = print;
            this.lock = lock;
            this.await = await;
            this.signalAll = signalAll;

        }

        public String print;

        Lock lock;

        Condition await;

        Condition signalAll;





        public void print(){
            System.out.println(Thread.currentThread().getName()+" Lock  : "+print);
            integer++;
        }


        @Override
        public void run(){
            System.out.println(Thread.currentThread().getName()+" Lock run start");
            while(true){
                try {
                    lock.lock();
                    if(!condition()){
                        await.await();
                    }
                    print();
                    signalAll.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }

            }
        }

        public   boolean condition(){
            if("A".equals(print)&&(integer % 3 == 0)){
                return true;
            }
            if("B".equals(print)&&(integer % 3 == 1)){
                return true;
            }
            if("C".equals(print)&&(integer % 3 == 2)){
                return true;
            }
            return false;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值