zoukankan      html  css  js  c++  java
  • 子线程和 主线程 互换

    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();
    	}
    
    }
    

      

  • 相关阅读:
    位运算操作
    C 动态分配内存
    数据查询语言 DQL
    数据操纵语言 ,DML, 增删改
    Convert Sorted List to Binary Search Tree
    Longest Consecutive Sequence
    Binary Tree Postorder Traversal
    Triangle
    4Sum
    3Sum Closest
  • 原文地址:https://www.cnblogs.com/GotoJava/p/7076737.html
Copyright © 2011-2022 走看看