多线程技术: 两个线程交替打印奇数和偶数
1. 要打印的资源
1 package com.mytest.thread; 2 3 /** 4 * 要打印的资源 5 * 6 */ 7 public class Num { 8 int i = 1; 9 // 两个线程看, 交替执行的一个标志 10 boolean flag = false; 11 }
2. 打印奇数的线程
1 package com.mytest.thread; 2 3 public class PrintOdd implements Runnable { 4 Num num; 5 6 public PrintOdd(Num num) { 7 this.num = num; 8 9 } 10 11 public void run() { 12 while (num.i <= 100) { 13 synchronized (num) { 14 if (num.flag) { 15 try { 16 num.wait(); 17 } catch (Exception e) { 18 System.out.println(e.getMessage()); 19 } 20 21 } else { 22 System.out.println("奇数----" + num.i); 23 num.i++; 24 num.flag = true; 25 num.notify(); 26 } 27 28 } 29 } 30 } 31 }
3. 打印偶数的线程
1 package com.mytest.thread; 2 3 public class PrintEven implements Runnable { 4 5 Num num; 6 7 public PrintEven(Num num) { 8 this.num = num; 9 10 } 11 12 public void run() { 13 while (num.i <= 100) { 14 synchronized (num) {// 必须要用同意吧锁对象,这个对象是num 15 if (!num.flag) { 16 try { 17 num.wait();// wait()函数必须和锁死同一个 18 } catch (Exception e) { 19 System.out.println(e.getMessage()); 20 } 21 22 } else { 23 System.out.println("偶数----" + num.i); 24 num.i++; 25 num.flag = false; 26 num.notify(); 27 } 28 29 } 30 } 31 } 32 33 }
4. 主函数
1 package com.mytest.thread; 2 3 public class Main { 4 public static void main(String[] args) { 5 6 Num num = new Num(); 7 8 PrintOdd printOdd = new PrintOdd(num); 9 PrintEven printEven = new PrintEven(num); 10 11 Thread thread1 = new Thread(printOdd); 12 Thread thread2 = new Thread(printEven); 13 14 thread1.start(); 15 thread2.start(); 16 } 17 }
5. 运行结果
♥作者:明志健致远
♠出处:http://www.cnblogs.com/study-everyday/
♦本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
♣本博客大多为学习笔记或读书笔记,本文如对您有帮助,还请多推荐下此文,如有错误欢迎指正,相互学习,共同进步。