程序员社区

多线程编程练习

一、多线程交替打印ABC

建立三个线程A、B、C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印。

1.1 synchronized同步

public class test {

    public static class ThreadPrinter implements Runnable{
        private String name;
        private Object prev;
        private Object self;

        private ThreadPrinter(String name,Object prev,Object self){
            this.name=name;
            this.prev=prev;
            this.self=self;
        }

        @Override
        public void run(){
            int count=10;
            while (count>0){
                synchronized (prev){
                    synchronized (self){
                        System.out.println(name);
                        count--;
                        self.notifyAll();
                    }
                    try {
                        if(count==0){
                            prev.notifyAll();
                        }else {
                            prev.wait();
                        }
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws Exception{
        Object a=new Object();
        Object b=new Object();
        Object c=new Object();
        ThreadPrinter pa=new ThreadPrinter("A",c,a);
        ThreadPrinter pb=new ThreadPrinter("B",a,b);
        ThreadPrinter pc=new ThreadPrinter("C",b,c);

        new Thread(pa).start();
        Thread.sleep(10);
        new Thread(pb).start();
        Thread.sleep(10);
        new Thread(pc).start();
        Thread.sleep(10);

    }

}

输出:

A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C

多线程交替打印ABC的多种实现方法

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 多线程编程练习

一个分享Java & Python知识的社区