zoukankan      html  css  js  c++  java
  • java--两线程通信

    package com.mythread;

    import java.io.IOException;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;

    public class danlie {

    public static void main(String[] args) throws  InterruptedException {
    	//extracted_1();
    	final Printer p =new Printer();
    	new Thread() {
    		public void run() {
    			while (true) {
    				try {
    					p.print1();
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    	}.start();
    	new Thread() {
    		public void run() {
    			while (true) {
    				try {
    					p.print2();
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    	}.start();
    	
    }
    

    class Printer{
    private int flag =1;
    Demo d =new Demo();
    public synchronized void print1() throws Exception {
    //synchronized(d){
    if(flag !=1) {
    this.wait();
    }
    System.out.print("test1");
    System.out.print("test2");
    System.out.print("test3");
    System.out.print("test4");
    System.out.print(" ");
    flag =2;
    this.notify();
    //}
    }
    public synchronized void print2() throws Exception {
    //synchronized(d){
    if(flag !=2) {
    this.wait();
    }
    System.out.print("print5");
    System.out.print("print6");
    System.out.print("print7");
    System.out.print(" ");
    flag =1;
    this.notify();
    //}
    }

    }

    ******************************人因为有理想、梦想而变得伟大,而真正伟大就是不断努力实现理想、梦想*****************************
  • 相关阅读:
    Less-21
    Less-22
    Less-21
    Less-20
    ssrf redis gopher
    Less19
    Less18
    Arm 系统查看、修改系统时间
    通过 grpc 请求标头发送自定义数据
    gRpc 空参数
  • 原文地址:https://www.cnblogs.com/cloudLi/p/13085377.html
Copyright © 2011-2022 走看看