Experiment with interview programming questions

Yesterday, a well-known Internet company had a phone interview with me. Then asked me to do a programming problem on a URL he gave.
The subject is this. There are 9 apples in total, and there are 2 monkeys. One monkey takes 2 apples each time, and one monkey takes 3 apples each time. If the remaining apples are not enough for the monkeys to take each time, the 2 monkeys stop taking apples, please use The description above of java multithreading simulation The description is quite simple. But in the case of a phone interview, it is a time-limited time for a relatively well-known company. I was nervous, and I wrote code in a non-IDE environment and couldn't remember many APIs, so I wrote the weird version below. What a shame.












//monkey2 is similar to monkey1. At that time, I was nervous before I finished writing, and then my network suddenly became abnormal, and then it was disconnected. Destined to be unable to seize the opportunity to perform well
private static volatile int appleStoreCount = 9;

public static void main(String... args) {
  
  ReentrantLock lock = new ReentrantLock();
	Runnable monkey1 = () -> {
      
      int takeOffNum = 2;
      
      outer : while(true){
        lock.lock()
       while( appleStoreCount >= takeOffNum) {
         
         appleStoreCount -= takeOffNum;
         lock.unlock();// This business simply assumes that there is no exception, so it is not put in finally
         continue outer;
       }
        break;
      };
    };
   Runnable monkey2 = () -> {
     
    int takeOffNum = 3;
      while( appleStoreCount.get() > = takeOffNum){
       
         if (appleStoreCount.compareAndDecrement(takeOffNum) == false){
        	
           continue;
         }
      };
   };
  
  Thread monkey1Task = new Thread(monkey1);
  Thread monkey2Task = new Thread(monkey2);
  monkey1Task.start();
  monkey1Task.start();
     
     
     
   }




But this code is really not what I originally envisioned. I really don't know what's going on in my heart.
The following is the code I wrote in the IDE environment after I calmed down and did not query the information.




private static final AtomicInteger STORE_COUNT = new AtomicInteger(9);

@Test
	public void tttt() {

		Runnable monkey1 = () -> {

			String monkeyName = "monkey1";
			int takeoffNum = 2,
					storeCountByGet = 0;
			while ((storeCountByGet = STORE_COUNT.get()) >= takeoffNum) {

				if (STORE_COUNT.compareAndSet(storeCountByGet, storeCountByGet - takeoffNum)) {

					System.out.println(monkeyName + "Success in grabbing fruit => " + takeoffNum);
				} else {

					System.out.println(monkeyName + "Failed to compete for fruit");
				}
			}
		};
		Runnable monkey2 = () -> {

			String monkeyName = "monkey2";
			int takeoffNum = 3,
					storeCountByGet = 0;
			while ((storeCountByGet = STORE_COUNT.get()) >= takeoffNum) {

				if (STORE_COUNT.compareAndSet(storeCountByGet, storeCountByGet - takeoffNum)) {

					System.out.println(monkeyName + "Success in grabbing fruit => " + takeoffNum);
				} else {

					System.out.println(monkeyName + "Failed to compete for fruit");
				}
			}
		};

		Thread m1Task = new Thread(monkey1);
		Thread m2Task = new Thread(monkey2);
		m2Task.start();
		m1Task.start();
	}


The output is as follows
monkey2 failed to scramble for fruit
monkey1 scramble for fruit successfully => 2
monkey2 scramble for fruit successfully => 3
monkey1 scramble for fruit successfully => 2
monkey1 scramble for fruit successfully => 2


This one is the implementation I originally envisioned. It can only be said that poor psychological quality and non-IDE environment led to abnormal performance. What a pity. This implementation is not perfect, but it is a clean implementation that meets the requirements.


——————————————— The dividing line that I don’t want to be ignored —————————

This part is an extended question that came to my mind when I saw the title. There are 9 apples in total, and there are 2 monkeys. One monkey takes 2 apples each time, and one monkey takes 3 apples each time. If the remaining apples are not enough for the monkeys to take each time, 2 monkeys stop taking apples, and two monkeys stop taking apples. The monkeys take the apples in turn. Please simulate the above description with java multithreading Here is my implementation








private volatile Integer[] storeCount = { 9 };

	private volatile int flagInt = 2;

	@Test
	public void tttt1() {

		Runnable monkey1 = () -> {

			String monkeyName = "monkey1";
			int takeoffNum = 2,
					flagVal = 1;

			synchronized (storeCount) {

				try {
					while (storeCount[0].intValue() >= takeoffNum) {
						if (flagInt != flagVal) {

							storeCount.wait();
						}
						if (storeCount[0].intValue() >= takeoffNum) {

							storeCount[0] -= takeoffNum;
							System.out.println(monkeyName + "Success in grabbing fruit => " + takeoffNum);
							flagInt = 2;
							storeCount.notifyAll();
						}
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
			}

		};
		Runnable monkey2 = () -> {

			String monkeyName = "monkey2";
			int takeoffNum = 3,
					flagVal = 2;

			synchronized (storeCount) {

				try {
					while (storeCount[0].intValue() >= takeoffNum) {
						if (flagInt != flagVal) {

							storeCount.wait();
						}
						if (storeCount[0].intValue() >= takeoffNum) {

							storeCount[0] -= takeoffNum;
							System.out.println(monkeyName + "Success in grabbing fruit => " + takeoffNum);
							flagInt = 1;
							storeCount.notifyAll();
						}
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
			}
		};

		Thread m1Task = new Thread(monkey1);
		Thread m2Task = new Thread(monkey2);
		m1Task.start();
		m2Task.start();
	}


The output is as follows
monkey2 scramble for fruit successfully => 3
monkey1 scramble for fruit successfully => 2
monkey2 scramble for fruit successfully => 3


The output after changing the initial value of flagInt to 1 is as follows
monkey1 scramble for fruit successfully => 2
monkey2 scramble for fruit successfully => 3
monkey1 scramble for fruit successfully => 2

Guess you like

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