//张老师的线程课程里面讲的知识很详细的- package cn.itcast.Test;
- public class ThreadTest2 {
- /**
- * @param args
- */
- /** 开启2条线程, 线程1中循环打印A, 线程2中循环打印B
- * 打印1次A, 打印1次B, 两条线程交替执行5次*/
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- final Print print=new Print();
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for(int i=0;i<5;i++){
- print.printA();
- }
- }
- }).start();
-
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- // TODO Auto-generated method stub
-
- for(int i=0;i<5;i++){
- print.printB();
- }
- }
- }).start();
-
- }
- }
- class Print{
- private boolean flase=true;
- public synchronized void printA(){
- while(!flase){
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("printA");
- flase=false;
- this.notify();
- }
- public synchronized void printB(){
- while(flase){
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("printB");
- flase=true;
- this.notify();
-
- }
- }
复制代码 |