Java之【线程通信】--标志位练习2
生活随笔
收集整理的這篇文章主要介紹了
Java之【线程通信】--标志位练习2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義一個線程A,輸出1 ~ 10之間的整數,定義一個線程B,逆序輸出1 ~ 10之間的整數,要求線程A和線程B交替輸出
方法一:非標志位方法
package Homework; //1 定義一個線程A,輸出1 ~ 10之間的整數,定義一個線程B,逆序輸出1 ~ 10之間的整數,要求線程A和線程B交替輸出 public class Test1 {public static void main(String[] args){Object obj=new Object();A a=new A(obj);B b=new B(obj);a.start();b.start();}}class A extends Thread{Object obj;public A() {super();}public A(Object obj) {super();this.obj = obj;}//正序打印@Overridepublic void run() {synchronized (obj) {for(int i=1;i<11;i++){System.out.print(i+",");obj.notify();try {obj.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}} } class B extends Thread{Object obj;public B() {super();}public B(Object obj) {super();this.obj = obj;}//逆序打印@Overridepublic void run() {try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}synchronized (obj) {for(int i=10;i>0;i--){System.out.print(i+",");obj.notify();if(i>1){try {obj.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}} }運行結果:
方法二:采用標志位
package Homework; //1 定義一個線程A,輸出1 ~ 10之間的整數,定義一個線程B,逆序輸出1 ~ 10之間的整數,要求線程A和線程B交替輸出 public class Test2 {public static void main(String[] args){C c=new C();A1 a1=new A1(c);B1 b1=new B1(c);a1.start();b1.start();} } class A1 extends Thread{C c;public A1(C c) {super();this.c = c;}public A1() {super();}@Overridepublic void run() {synchronized (c) {for(int i=1;i<11;i++){if(c.flag==true){try {c.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}c.print(i);c.flag=true;c.notify();}}}} class B1 extends Thread{C c;public B1(C c) {super();this.c = c;}public B1() {super();}@Overridepublic void run() {synchronized (c) {for(int i=10;i>0;i--){if(c.flag==false){try {c.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}c.print(i);c.flag=false;c.notify();}}} } class C {boolean flag=false;//true A已經打印,B為打印 A等待public void print(int i){System.out.print(i+",");} }運行結果
總結
以上是生活随笔為你收集整理的Java之【线程通信】--标志位练习2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java之【线程通信】--标志位练习
- 下一篇: Java之枚举