Java多线程-三个线程循环打印ABC(一)

2017/05/04 Java,多线程

Java三个线程循环打印ABC。。。,是个笔试题,主要学习掌握线程同步,需要有线程基础知识。 思路:通过synchronized关键词锁定对象让线程同步,根据取模运算符%交替打印,每打印一次并唤醒其他睡眠线程同时使自身线程Wait,依次循环。

定义一个线程执行主体

/**
 * Created by litf on 2017/5/4.
 */
public class RunnableAbc  implements Runnable{

    private Integer id;
    private String name;
    private Integer count=3;
    private static Integer sums = 1;
    private final static Object object = new Object();

    public RunnableAbc(Integer id,String name){
        this.id = id;
        this.name = name;
    }
    @Override
    public void run() {

        while(true){
            synchronized (object){
                if(sums % count == id){
                    System.out.print(name);
                    sums++;
                    object.notifyAll();
                    if(name.equals("C"))
                        System.out.println();
                }else if(sums >30){
                    object.notifyAll();
                    break;
                }else{
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}

调用打印ABC

/**
 * Created by litf on 2017/5/4.
 */
public class RunableTest {
    public static void main(String args[]){

        new Thread(new RunnableAbc(1,"A")).start();
        new Thread(new RunnableAbc(2,"B")).start();
        new Thread(new RunnableAbc(0,"C")).start();

    }
}

打印结果:

ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
AB
Show Disqus Comments

Search

    Post Directory