码迷,mamicode.com
首页 > 编程语言 > 详细

子线程和 主线程 互换

时间:2017-06-25 14:55:52      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:完整   之间   art   notifyall   thread   ble   style   star   方法   

package demo;

/**
 * 子线程循环5次,主线程循环10次。依次交替。整个交替循环3次
 *
 */
public class ThreadTest {
	public static void main(String[] args) {
		init();
	}
	
	static void init(){
		final Print p = new Print();//封装了 循环的动作
		new Thread(new Runnable(){

			@Override
			public void run() {
				for(int i=0;i<3;i++){
						p.subPrint(5);//循环5次
					}
				}
		}).start();
		
		new Thread(new Runnable(){
			
			@Override
			public void run() {
				for(int i=0;i<3;i++){
					p.mainPrint(10);//循环10次
				}
			}
			
		}).start();
	}

}

  

Print:

package demo;

/**
 * 两个方法之间互斥 (方法里面完整执行完),用 Sflag实现 开关控制 两个方法的切换
 *
 */
public class Print {
	boolean Sflag = true;
	public synchronized void subPrint(int num){
		while(!Sflag){//避免 伪唤醒
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i=1;i<=num;i++){
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
		Sflag = false;
		this.notifyAll();
	}
	public synchronized void mainPrint(int num){
		while(Sflag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i=1;i<=num;i++){
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
		Sflag = true;
		this.notifyAll();
	}

}

  

子线程和 主线程 互换

标签:完整   之间   art   notifyall   thread   ble   style   star   方法   

原文地址:http://www.cnblogs.com/GotoJava/p/7076737.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!