58

如何让两个线程“系鞋带"

 3 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzI3MDU3OTc1Nw%3D%3D&%3Bmid=2247484868&%3Bidx=1&%3Bsn=5b3cf0cf6f384e1c62e820d4c27047c1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

neANfy7.png!web

前两天转了马士兵老师的《没错,我就是厕所所长!》,正好有朋友和我讨论一个线程打印的问题,于是今天就趁着周末们睡觉,写了个简单的实现。

题干,是这样的,通过2个线程,交替输出 A1B2C3....Z26

先贴出我的实现,欢迎大家和我讨论

public class TwoThread2 {
    public static class Printer{
        public synchronized void print(String i) {
            try {
                this.notify();
                System.out.println(Thread.currentThread().getName() + " " + i);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //两个线程交替输出, A1B2C3.....Z26
    public static final int SETPS = 26;
    public static class ThreadNum extends Thread {
        private int startCharCount = 1;
        private Printer p = new Printer();
        public Printer getP() {
            return p;
        }
        public void setP(Printer p) {
            this.p = p;
        }
        @Override
        public void run() {
            for (int i = 0; i < SETPS; i++) {
                p.print(startCharCount+++"");
            }
        }
    }
    public static class ThreadStr extends Thread {
        private int startCharCount = 65;
        private Printer p = new Printer();
        public Printer getP() {
            return p;
        }
        public void setP(Printer p) {
            this.p = p;
        }
        @Override
        public void run() {
            for (int i = 0; i < SETPS; i++) {
                p.print( (char) startCharCount+++"");
            }
        }
    }
    public static void main(String[] args) {
        Printer p = new Printer();
        ThreadNum tn = new ThreadNum();
        tn.setName("Thread num :");
        tn.setP(p);
        ThreadStr ts = new ThreadStr();
        ts.setName("Thread str :");
        ts.setP(p);
        ts.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tn.start();
    }
}

大概实现就是这样的,这个流程有点想系鞋带,用一个线程专门打印字符串,一个线程打印数字,然后线程交替加锁,释放,流程大概如下所示。

jqmIrqq.png!web

如果文章对您有那么一点点帮助,我将倍感荣幸,

欢迎 关注、在看、点赞、转发 

yQvmuye.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK