美文网首页
如何实现两个线程间隔打印?

如何实现两个线程间隔打印?

作者: 稀饭粥95 | 来源:发表于2018-08-21 20:16 被阅读3次

使用lock锁

public class Main{
    public static Lock lock = new ReentrantLock();
    public static int i=0;
    public static void main(String[] args)  {
        
        Thread th1 = new Thread("1"){
            public void run(){
                while(i<=100){
                    lock.lock();
                    if(i%2==1&&i<=100){
                        System.out.println(Thread.currentThread().getName()+" "+i);
                        i++;
                        
                    }
                    lock.unlock();
                }
                
            }
        };
        
        Thread th2 = new Thread("2"){
            public void run(){  
                while(i<=100){
                    lock.lock();
                    if(i%2==0&&i<=100){
                        System.out.println(Thread.currentThread().getName()+" "+i);
                        i++;
                    }
                    lock.unlock();
                }
                
            }
        };
        th1.start();
        th2.start();
    }
}

相关文章

网友评论

      本文标题:如何实现两个线程间隔打印?

      本文链接:https://www.haomeiwen.com/subject/dpqsiftx.html