java thread problem

Please write a multi-threaded program to implement two threads, one of which completes the increase operation of the int member variable of an object, that is, adds 1 each time, and the other thread completes the subtraction operation of the member variable of the object, that is, every time Subtract 1 times, and at the same time ensure that the value of the variable will not be less than 0, not greater than 1, and the initial value of the variable will be 0.

 

package crease;

public class Sample {
	int number = 0;
	
	public synchronized void add(){
		while(number > 0){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
		number ++;
		System.out.print(number);
		notify();
	}
	
	public synchronized void jian(){
		while(number == 0){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
		number--;
		System.out.print(number);
		notify();
	}
}

 

package crease;

public class TestSample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Sample sample = new Sample();
		new AddThread(sample).start();
		new JianThread(sample).start();
	}

}

class AddThread extends Thread{
	private Sample sample;
	public AddThread(Sample sample){
		this.sample = sample;
	}
	
	public void run(){
		for(int i=0;i<10;i++){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
			sample.add();
		}
	}
}

class JianThread extends Thread{
	private Sample sample;
	public JianThread(Sample sample){
		this.sample = sample;
	}
	
	public void run(){
		for(int i=0;i<10;i++){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
			sample.jian();
		}
	}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326417697&siteId=291194637