自学内容网 自学内容网

Java经典面试题-多线程打印

thread+synchronized

就好像一个圆圈,A->B->C->A。。。。。

synchronized能够保证多个线程进入实,只用一个线程能进入。

/**多线程交替打印
 * */
public class Task {
    private final Object lock = new Object();
    private int count = 0;
    public static void main(String[] args) {

        Task task = new Task();
        new Thread(()->{
            for(int i=0;i<10;i++){
                task.printA();
            }
        }).start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                task.printB();
            }
        }).start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                task.printC();
            }
        }).start();

    }
    public void printA(){
        synchronized (lock){
            while(count!=0){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print("A");
            count++;
            lock.notifyAll();
        }
    }
    public void printB(){
        synchronized (lock){
           while(count!=1){
               try{
                   lock.wait();
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
           }
            System.out.print("B");
            count++;
            lock.notifyAll();
        }
    }
    public void printC(){
        synchronized (lock){
            while(count!=2){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print("C");
            count=0;
            lock.notifyAll();
        }
    }
}

ReentrantLock

public class Task2 {
      private  final Lock lock=new ReentrantLock();
      private final Condition condition=lock.newCondition();
      private final Condition condition1=lock.newCondition();
      private final Condition condition2=lock.newCondition();
      private int state=0;
    public static void main(String[] args) {
        Task2 tash2 = new Task2();
        Thread thread = new Thread(tash2::printA);
        Thread thread1 = new Thread(tash2::printB);
        thread.start();
        thread1.start();

    }
    private void printA(){
       // get lock
        lock.lock();
        try{
            for(int i=0;i<10;i++){
                while(state!=0){
                    condition.await();
                }
                System.out.print("a");
                state=1;
                condition1.signal();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
    private  void printB(){
        lock.lock();
        try{
            for(int i=0;i<10;i++){
                while(state!=1){
                    condition1.await();
                }
                System.out.print("b");
                state=0;
                condition.signal();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }

    }
}

Semaphore

信号量机制,设置刚开始的值为1,如果减去1的结果>=0,则执行该线程,否则不执行,执行完释放,值加1

public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)
            acquire(null, arg, true, false, false, 0L);
    }

    /**
     * Acquires in shared mode, aborting if interrupted.  Implemented
     * by first checking interrupt status, then invoking at least once
     * {@link #tryAcquireShared}, returning on success.  Otherwise the
     * thread is queued, possibly repeatedly blocking and unblocking,
     * invoking {@link #tryAcquireShared} until success or the thread
     * is interrupted.
     * @param arg the acquire argument.
     * This value is conveyed to {@link #tryAcquireShared} but is
     * otherwise uninterpreted and can represent anything
     * you like.
     * @throws InterruptedException if the current thread is interrupted
     */
    public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
        if (Thread.interrupted() ||
            (tryAcquireShared(arg) < 0 &&
             acquire(null, arg, true, true, false, 0L) < 0))
            throw new InterruptedException();
    }

package com.r.ThreadTask;

import javax.swing.text.Segment;
import java.util.concurrent.Semaphore;

public class Task3 {
    private final Semaphore semaphore=new Semaphore(1);
    private final Semaphore semaphore1=new Semaphore(0);
    private final Semaphore semaphore2=new Semaphore(0);
    public static void main(String[] args) {
        Task3 task3 = new Task3();
        Thread thread = new Thread(task3::printA);
        Thread thread1 = new Thread(task3::printB);
        Thread thread2 = new Thread(task3::printC);
        thread.start();
        thread1.start();
        thread2.start();
    }
    private void printA(){
        for(int i=0;i<10;i++){
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.print("a");
            semaphore1.release();
        }
    }
    private void printB(){
        for(int i=0;i<10;i++){
            try {
                semaphore1.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.print("b");
            semaphore2.release();
        }
    }
    private void printC(){
        for(int i=0;i<10;i++){
            try {
                semaphore2.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.print("c");
            semaphore.release();
        }
    }
}



原文地址:https://blog.csdn.net/weixin_73670733/article/details/142831744

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!