美文网首页
两个线程交替打印出26个小写字母

两个线程交替打印出26个小写字母

作者: cwjbest | 来源:发表于2018-12-07 18:49 被阅读13次

    今天去面试遇见这道题,当时觉得挺简单的,结果写起来一紧张卡壳了,回来想了一下,思路挺明确的,同一个类,两个线程访问它,一个打完之后将另一个唤醒就好了。
    代码如下:

    package com.cwj.thread;
    
    /**
     * Created by cwj on 18-12-7.
     */
    public class Print_letter implements Runnable{
        char ch = 97;
    
        @Override
        public void run() {
            while (true){
                synchronized (this){
                    notify();
                    try {
                        Thread.currentThread().sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
    
                    if (ch < 123){
                        System.out.println(Thread.currentThread().getName() + " " + ch);
                        ch++;
                        try {
                            wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            Print_letter t = new Print_letter();
            Thread t1 = new Thread(t);
            Thread t2 = new Thread(t);
            t1.start();
            t2.start();
        }
    }
    

    相关文章

      网友评论

          本文标题:两个线程交替打印出26个小写字母

          本文链接:https://www.haomeiwen.com/subject/ugdxhqtx.html