繁体   English   中英

在java中使用三个线程打印111222333

[英]print 111222333 using Three threads in java

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

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。

我想以下会帮助你。 它正在使用等待/通知。

    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();
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM