zoukankan      html  css  js  c++  java
  • [java多线程]数字加减 代码

    问题概述:设计四个线程对象,两个线程实现加操作,两个线程实现减操作

    注意一个问题:经常会用if(this.flag==false)来判断,用if并不能实现进程同步,会出现负数。

     class Resource{
    	private int num=0;//
    	private boolean flag=true;//加减操作
    	public synchronized void add() throws InterruptedException {
    		while(this.flag==false) {
    			super.wait();
    		}
    		Thread.sleep(400);
    		this.num++;
    		System.out.println("【加法操作】"+
    		Thread.currentThread().getName()
    				+"num="+this.num);
    		this.flag=false;
    		super.notifyAll();
    	}
    	public synchronized void sub() throws InterruptedException {
    		while(this.flag==true) {
    			super.wait();
    		}
    		Thread.sleep(600);
    		this.num--;
    		System.out.println("【减法操作】"+
    		Thread.currentThread().getName()
    		+"num="+this.num);
    		this.flag=true;
    		super.notifyAll();
    	}
    } 
     class AddThread  implements Runnable{
    	private Resource resource;
    	public AddThread(Resource resource) {
    		this.resource=resource;
    	}
    
    	@Override
    	public void run() {
    		for(int x=0;x<50;x++) {
    			try {
    				this.resource.add();
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		} 
    	}
    	
    } 
     
    
    class SubThread  implements Runnable{
    	private Resource resource;
    	public SubThread(Resource resource) {
    		this.resource=resource;
    	}
    	@Override
    	public void run() {
    		for(int x=0;x<50;x++) {
    			try {
    				this.resource.sub();
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	}
    }
     
    public class Test1 {
     public static void main(String[] args) throws Exception {
    		Resource resource = new Resource();
    		SubThread st = new SubThread(resource);
    		AddThread at = new AddThread(resource);
    		new Thread(at, "减法线程-A").start();
    		new Thread(at, "减法线程-B").start();
    	    
    		new Thread(st, "加法线程-a").start();
    		new Thread(st, "加法线程-b").start();
    		 
    }
    }
    
  • 相关阅读:
    MySQL Thread Pool: Problem Definition
    MySQL数据库InnoDB存储引擎多版本控制(MVCC)实现原理分析
    Mysql源码目录结构
    android学习18——对PathMeasure中getPosTan的理解
    android学习17——命令行建gradle工程
    android学习16——library project的使用
    android学习13——android egl hello world
    ant编译java的例子
    android学习12——重载SurfaceView一些方法的执行顺序
    Visual Studio命令行创建库文件lib
  • 原文地址:https://www.cnblogs.com/yxj808/p/12677165.html
Copyright © 2011-2022 走看看