面试宝典程序员技术文

多线程(一):经典面试题

2017-04-06  本文已影响628人  WhyNotYue

题目要求

设计一个程序,启动三个线程A,B,C,各个线程只打印特定的字母,各打印10次,例如A线程只打印‘A’。要求在控制台依次显示“ABCABC…”


实现代码

方式一:采用Object的wait,notify方法
/**
 * Created by 阿越 on 2017/4/5.
 */
// 方式一:采用wait,notify
public class PrintABC {
    public static void main(String[] args) throws InterruptedException {
        Object A = new Object();
        Object B = new Object();
        Object C = new Object();

        // 线程ta只有同时拥有A和B对象的锁时才会打印A,线程tb和tc类似。
        Thread ta = new Thread(new Print(A,B),"A");
        Thread tb = new Thread(new Print(B,C),"B");
        Thread tc = new Thread(new Print(C,A),"C");

        
        ta.start();
        Thread.sleep(1000);// 为了保证初始执行顺序为A->B->C
        tb.start();
        Thread.sleep(1000);
        tc.start();
    }
}

class Print implements Runnable{
    private Object self;
    private Object next;

    public Print(Object self, Object next) {
        this.self = self;
        this.next = next;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (self) {
                // synchronized (next) {}执行完毕后,next对象的锁也就释放了
                synchronized (next) {
                    // 当且仅当同时拥有自身对象锁和下一个对象的锁时才会打印
                    System.out.print(Thread.currentThread().getName());
                    // 打印成功,唤醒下一个
                    next.notify();
                }
                // 没有持有next锁或者打印后next锁释放了,则等待
                try {
                    // 最后一个,不用等待
                    if (i==9){
                        return;
                    }
                        self.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
方式二:采用Lock和Condition的方式
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by 阿越 on 2017/4/5.
 */
// 方式二,采用ReentrantLock和Condition
public class PrintABC_Condition {
    // 设置一个标识,谁先打印初始值设置为谁,这里先打印A
    private String flag = "A";

    // Lock锁对象
    private Lock lock = new ReentrantLock();

    // 通过锁对象获取Condition
    private Condition ca = lock.newCondition();
    private Condition cb = lock.newCondition();
    private Condition cc = lock.newCondition();

    private Thread a;
    private Thread b;
    private Thread c;

    public void printA() {
        // 加锁
        lock.lock();
        try {
            // 判断标识是否是当前要打印的值;否,等待;是,打印;
            if (!flag.equals("A")) {
                ca.await();// objA.wait();
            }
            System.out.print(Thread.currentThread().getName());
            // 打印完,把标识修改为下一个要打印的值
            flag = "B";
            // 唤醒下一个Condition
            cb.signal();// objB.notify();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();// 释放锁
        }
    }

    public void printB() {
        lock.lock();
        try {
            if (!flag.equals("B")) {
                cb.await();
            }
            System.out.print(Thread.currentThread().getName());
            flag = "C";
            cc.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            if (!flag.equals("C")) {
                cc.await();
            }
            System.out.print(Thread.currentThread().getName());
            flag = "A";
            ca.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public PrintABC_Condition() {
        a = new Thread("A") {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 10; i++) {
                    printA();
                }
            }
        };
        b = new Thread("B") {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 10; i++) {
                    printB();
                }
            }
        };
        c = new Thread("C") {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 10; i++) {
                    printC();
                }
            }
        };
    }

    public void start(){
        a.start();
        b.start();
        c.start();
    }

    public static void main(String[] args) {
        new PrintABC_Condition().start();
    }
}

方式三:采用信号量Semaphore

Semaphore是一种基于计数的信号量。可以控制某个资源可被同时访问的个数,线程通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

import java.util.concurrent.Semaphore;

/**
 * Created by 阿越 on 2017/4/5.
 */
// 方式三,采用Semaphore
public class PrintABC_Semaphore {

    public static void main(String[] args) {
        PrintABC_Semaphore exp = new PrintABC_Semaphore();
        exp.start();
    }

    // 设置A,B,C线程的信号量的初始许可为0
    Semaphore sa = new Semaphore(0);
    Semaphore sb = new Semaphore(0);
    Semaphore sc = new Semaphore(0);

    public Thread a;
    public Thread b;
    public Thread c;

    public PrintABC_Semaphore() {
        // 线程A
        a = new Thread() {
            @Override
            public void run() {
                super.run();
                // 因为从A开始打印,所以要先释放一个C许可
                sc.release();
                for (int i = 0; i < 10; i++) {
                    try {
                        // 获取C的许可,得到C的许可才会打印,得不到就阻塞
                        sc.acquire();
                        System.out.print("A");
                        // 打印完,释放一个A的许可
                        sa.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        b = new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 10; i++) {
                    try {
                        sa.acquire();
                        System.out.print("B");
                        sb.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        c = new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 10; i++) {
                    try {
                        sb.acquire();
                        System.out.print("C");
                        sc.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    public void start() {
        a.start();
        b.start();
        c.start();
    }
}


如果觉得文章对您有用,麻烦点击关注和喜欢,感谢支持!

上一篇下一篇

猜你喜欢

热点阅读