首页 > 解决方案 > 在java中使用三个线程打印111222333

问题描述

我使用连接方法打印序列。

public class SequencePrint {

    public static void main(String[] args) throws InterruptedException {
        Runnable r1 = new PrintSeq("1");
        Runnable r2 = new PrintSeq("2");
        Runnable r3 = new PrintSeq("3");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        Thread t3 = new Thread(r3);

        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
        t3.join();
        System.out.println("Main");
    }
}

class PrintSeq implements Runnable{

    private String seq = null;

    public PrintSeq(String seq) {
        this.seq = seq;
    }

    @Override
    public void run() {
        for(int i=0 ; i<10 ; i++) {
            System.out.print(seq);
        }
        System.out.println();
    }
}

有没有办法在等待通知或其他同步技术中使用三个线程打印 111122223333。

标签: java

解决方案


我想以下内容会对您有所帮助。它正在使用等待/通知。

    public class SequencePrint {
        static int data = 1;
        static final int SEQ_COUNT = 3;
        public static class Worker implements Runnable{
            private int id;
            private Object lock = null;
            @Override
            public void run() {
                int c = 0;
                synchronized (lock) {
                    try {
                        while(id != data) {
                            lock.wait();                    
                        }
                        while(c < SEQ_COUNT) {
                            c++;
                            System.out.print(id);
                        }
                        SequencePrint.data++;
                        lock.notifyAll();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            public Worker(int x, Object lock) {
                super();
                this.id = x;
                this.lock = lock;
            }

        }

        public static void main(String args[]) {
            Object lock = new Object();
            Runnable r1 = new Worker(1, lock);
            Runnable r2 = new Worker(2, lock);
            Runnable r3 = new Worker(3, lock);
            Thread t1 = new Thread(r1);
            Thread t2 = new Thread(r2);
            Thread t3 = new Thread(r3);
            t1.start();
            t2.start();
            t3.start();
        }

    }

推荐阅读