读书人

JAVA多线程-两个线程更迭运行

发布时间: 2013-04-12 18:33:12 作者: rapoo

JAVA多线程---两个线程交替运行



package com.mfz.test;public class TwoThread {private static Object lock = new Object();private static boolean flag = false;public static void main(String[] args) {Thread a = new Thread(){public void run(){while(true){synchronized(lock){System.out.println("Thread1");if(flag){flag = false;lock.notify();try {lock.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}};Thread b = new Thread(){public void run(){while(true){synchronized(lock){System.out.println("Thread2");if(!flag){flag =true;try {lock.notify();lock.wait();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}}}};a.start();b.start();}}

读书人网 >软件开发

热点推荐