面试经典题目:多线程循环打印

写法1:lock

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

public class UsingLock {
    Lock lock=new ReentrantLock();  // 保证每次只有一个线程能够拿到资源
    int time; // 控制打印次数
    int state=0; // 当前状态值:保证三个线程之间交替打印
    public UsingLock(int time) {
        this.time = time;
    }
    private void Print(String str,int flag){
        for(int i=0;i

面试经典题目:多线程循环打印_第1张图片 

写法2:Usingsemaphore

import java.util.concurrent.Semaphore;

public class Usingsemaphore {
    private int time;
    private int num=0;
    private char ch='a';
    private char chA='A';
    private Semaphore a=new Semaphore(1);
    private Semaphore b=new Semaphore(0);
    private Semaphore c=new Semaphore(0);
    public Usingsemaphore(int time) {
        this.time = time;
    }
    private void PrintA(){
        try{
           Print("A",a,b);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void PrintB(){
        try{
            Print("B",b,c);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void PrintC(){
        try{
            Print("C",c,a);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void Print(String str,Semaphore current,Semaphore next){
        try{
            for(int i=0;i

写法3:Wait Notify synchronized

public class Usingwaitnotify {
    int time;
    int state=0;
    private Object a = new Object();
    private Object b = new Object();
    private Object c = new Object();
    public Usingwaitnotify(int time) {
        this.time = time;
    }

    private void Print(String str,int flag,Object a,Object b) throws Exception{
        for(int i=0;i

 面试经典题目:多线程循环打印_第2张图片

你可能感兴趣的:(面试经典题目:多线程循环打印)