繁体   English   中英

如何通过两个线程打印非重复元素?

[英]How to print non repeating element by two threads?

我想通过两个线程从同一资源打印非重复元素。

在下面的代码中,正在打印重复的元素

class TestSleepMethod1 extends Thread{  
    public void run(){  
        for(int i=1;i<5;i++){  
            try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
            System.out.println(i);  
        }  
    }

    public static void main(String args[]){  
        TestSleepMethod1 t1=new TestSleepMethod1();  
        TestSleepMethod1 t2=new TestSleepMethod1();  

        t1.start();  
        t2.start();  
    }  
}  

输出 :

1 1 2 2 3 3 4 4 我想要,如果一个线程打印“ 1”,另一个线程不应再次打印“ 1”,而是应该打印2。 如何达到这个条件? 谢谢。

您可以拥有一个队列(例如:BolockingQueue)并将所有数字添加到其中。 然后在添加之后通知线程,该线程应该一个一个地从队列中获取值。 这将帮助您实现所需的结果。 请参阅http://tutorials.jenkov.com/java-concurrency/blocking-queues.html

在您的情况下,由于线程处于休眠状态,这种情况极不可能发生。

尝试使用不同的睡眠间隔:

class TestSleepMethod1 extends Thread {
    private final long sleepingInterval;

    private TestSleepMethod1(long sleepingInterval) {
        this.sleepingInterval = sleepingInterval;
    }

    public void run(){  
        for(int i=1;i<5;i++){  
            try{Thread.sleep(sleepingInterval);}catch(InterruptedException e){System.out.println(e);}  
            System.out.println(i);  
        }  
    }

    public static void main(String args[]){  
        TestSleepMethod1 t1=new TestSleepMethod1(500);  
        TestSleepMethod1 t2=new TestSleepMethod1(300);  

        t1.start();  
        t2.start();  
    }  
}  
try 



    static int i =1;
    public void run(){ 
        for(;i<5;){  // you can also use while(i<5)
            try{
                Thread.sleep(500);

            }catch(InterruptedException e){
                System.out.println(e);
            }  
            System.out.println(i++); 
        }  
    }  
    public static void main(String args[]){  
        TestSleepMethod1 t1=new TestSleepMethod1();  
        TestSleepMethod1 t2=new TestSleepMethod1();  

        t1.start();  
        t2.start();  
    }  


output 
1
2
3
4

您必须使用强制执行操作原子性的共享和线程安全结构。

AtomicInteger适合您的需求。 AtomicInteger#incrementAndGet是一个原子操作。 结果,对于一个distinctct值,只有一个线程将递增该值并返回它:

class TestSleepMethod1 extends Thread{  
    private static final AtomicInteger counter = new AtomicInteger(0);
    public void run(){  
        for(int i=1;i<5;i++){  
            try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
            System.out.println(counter.incrementAndGet());  
        }  
    }

    public static void main(String args[]){  
        TestSleepMethod1 t1=new TestSleepMethod1();  
        TestSleepMethod1 t2=new TestSleepMethod1();  

        t1.start();  
        t2.start();  
    }  
}  

暂无
暂无

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

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