면접 의 손 찢 기 코드

7135 단어
머리말
본 고 는 자신의 학습 기록 을 위해 면접 에서 만난 손 찢 기 코드 (비 알고리즘 문제) 를 기록 하 는 것 도 자신의 복습 이 편리 하 다.
 
2. 디자인 모델
1. 공장 모델
(1) 단순 공장
//       
public interface Product {
    void getInfo();
}
//     A
public class ProductA implements Product {
    @Override
    public void getInfo() {
        System.out.println("I am productA");
    }
}
//     B
public class ProductB implements Product {
    @Override
    public void getInfo() {
        System.out.println("I am productB");
    }
}
//    ,         
public class Factory {
    private Product product;
    public Factory() {

    }
    public Product getProductA() {
        product = new ProductA();
        return product;
    }

    public Product getProductB() {
        product = new ProductB();
        return product;
    }

    public static void main(String[] args) {
        Factory factory = new Factory();
        Product productA = factory.getProductA();
        Product productB = factory.getProductB();
        productA.getInfo();
        productB.getInfo();
    }
}

(2) 추상 공장
//        ProductA ProductB
//      
public interface Factory {
    Product getProduct();
}
//     A
public class ProductAFactory implements Factory {
    @Override
    public Product getProduct() {
        return new ProductA();
    }
}
//     B
public class ProductBFactory implements Factory {
    @Override
    public Product getProduct() {
        return new ProductB();
    }
}
//    
public class Main   {
    public synchronized static void main(String[] args) {
        Factory factoryA = new ProductAFactory();
        Product productA = factoryA.getProduct();
        Factory factoryB = new ProductBFactory();
        Product productB = factoryB.getProduct();
        productA.getInfo();
        productB.getInfo();
    }
}

2. 단일 모드
(1) 이중 검사 자물쇠
public class Singleton {
    private static volatile Singleton INSTANCE = null;
    private Singleton(){};
    public Singleton getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton();
                }
                return INSTANCE;
            }
        }
        return INSTANCE;
    }
}

(2) 정적 내부 클래스
public class Singleton {
    private Singleton(){};
    static class SingletonHelper {
        private static Singleton INSTANCE = new Singleton();
    }
    public Singleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}

3. 전략 모드
//      
public interface Strategy {
    void getInfo();
}
//   A
public class StrategyA implements Strategy {
    @Override
    public void getInfo() {
        System.out.println("I am StrategyA.");
    }
}
//   B
public class StrategyB implements Strategy {
    @Override
    public void getInfo() {
        System.out.println("I am StrategyB.");
    }
}
//      
public class Context {
    private Strategy strategy;
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void doSomeThing() {
        strategy.getInfo();
    }

    public static void main(String[] args) {
        Context context = new Context(new StrategyA());
        context.doSomeThing();
    }
}

병발
1. 읽 기와 쓰기 자물쇠
(1) synchronized 실현
    class MyReadWriteLock{
        private volatile int read;
        private volatile int write;
        public MyReadWriteLock(){
            read = 0;
            write = 0;
        }
        public synchronized void readLock() throws InterruptedException {
            while (write != 0) {
                wait();
            }
            read ++;
        }
        public synchronized void unlockRead() {
            read --;
            notifyAll();
        }
        public synchronized void writeLock() throws InterruptedException {
            while (write != 0 || read != 0) {
                wait();
            }
            write ++;
        }
        public synchronized void unlockWrite() {
            write --;
            notifyAll();
        }
    }

(2) 신 호 량 실현
    class ReaderAndWriter{
        private Semaphore readSemaphore = new Semaphore(1);
        private Semaphore writerSemaphore = new Semaphore(1);
        private int count = 0;
        public void readLock() throws InterruptedException {
            readSemaphore.acquire();
            if (count == 0) {
                writerSemaphore.acquire();
            }
            ++count;
            readSemaphore.release();
        }

        public void readUnlock() throws InterruptedException {
            readSemaphore.acquire();
            --count;
            if (count == 0) {
                writerSemaphore.release();
            }
            readSemaphore.release();
        }

        public void writeLock() throws InterruptedException {
            writerSemaphore.acquire();
        }

        public void writeUnlock() {
            writerSemaphore.release();
        }
    }

2. 생산자 소비자
1. 신 호 량 실현
import java.util.concurrent.Semaphore;

public class ProduceAndConsume {
    private int cacheSize = 0;
    private Semaphore mutex;
    private Semaphore full;
    private Semaphore empty;

    public ProduceAndConsume(int size) {
        mutex = new Semaphore(1);
        full = new Semaphore(0);
        empty = new Semaphore(size);
    }

    public void produce() throws InterruptedException {
        empty.acquire();
        mutex.acquire();
        cacheSize ++;
        System.out.println("produce..");
        mutex.release();
        full.release();
    }

    public void consume() throws InterruptedException {
        full.acquire();
        mutex.acquire();
        cacheSize --;
        System.out.println("consume");
        mutex.release();
        empty.release();
    }
}

 
정렬
1. 빠 른 배열 (가장 좋 은 상황 nlogn, 최 악의 n2, 숫자 정렬 또는 역순)
    public void quickSort(int[] nums, int left, int right) {
        if (left >= right) return;
        int key = nums[left];
        int pLow = left;
        int pHigh = right;
        while (pLow < pHigh) {
            //         ,           
            while (nums[pHigh] >= key && pLow < pHigh) {
                --pHigh;
            }
            while (nums[pLow] <= key && pLow < pHigh) {
                ++pLow;
            }
            if (pLow < pHigh) {
                int tmp = nums[pLow];
                nums[pLow] = nums[pHigh];
                nums[pHigh] = tmp;
            }
        }
        nums[left] = nums[pLow];
        nums[pLow] = key;
        quickSort(nums,left,pLow-1);
        quickSort(nums,pLow+1,right);
    }

좋은 웹페이지 즐겨찾기