• [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存儲過程+游標的應用實例5/17
    mysql存儲過程+遊標應用之:找缺號5/19
    轉:愚公移山
    c++中的头文件
    栈和堆:生存空间
    java中的类加载
    c++中的连接
    访问static变量和方法
    子类调用构造函数的过程
    c++中变量的存储种类
  • 原文地址:https://www.cnblogs.com/yxj808/p/12677165.html
Copyright © 2020-2023  润新知