一、仅使用synchronized来实现
通过创建两个线程,这两个线程共享object对象锁,当一个线程打印完一个数字后,会释放对象锁,另一个线程拿到对象锁,然后判断是否为偶数(奇数),满足条件则打印。
public class PrintNumTest1 { private static final Object obj = new Object(); private static int count = 0; private static int num = 1000; public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { while (count <= num) { synchronized (obj){ if((count&1) == 0) { System.out.println(Thread.currentThread().getName()+ ++count); } } } } }, "奇数线程").start(); new Thread(new Runnable() { @Override public void run() { while (count <= num) { synchronized (obj){ if((count&1) == 1) { System.out.println(++count); } } } } }, "偶数线程").start(); } }
二、使用notify()/wait()和synchronized实现
此种方式,写法简洁,让线程拿到对象锁后,立即打印数字,然后通过notify()释放锁,然后调用wait()方法使线程进入等待状态。另一个线程拿到锁以后,也立即打印数字,然后通过notify()释放锁,然后进入等待状态。知道打印完100以内的所有数字,两个线程都能正常停止运行。
public class PrintNumTest2 { private static final Object obj = new Object(); private static int count = 0; public static void main(String[] args) { new Thread(new PrintNum(),"多线程A").start(); new Thread(new PrintNum(),"多线程B").start(); } static class PrintNum implements Runnable { @Override public void run() { while (count < 100) { synchronized (obj) { System.out.println(Thread.currentThread().getName()+":"+ ++count); obj.notify(); try { obj.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } } }
 
 
                     
                    
                 
                    
                 

 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号