首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

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

2024-12-21 来源:要发发知识网

使用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();
    }
}
显示全文