Java Exercise - Multithreading

1. Use the Runnable interface to create three sub-threads and name them A, B, and C to simulate the ticket selling operation, and observe the results
/*
 * Use the Runnable interface to create three sub-threads and name them A, B, and C to simulate the ticket selling operation, and observe the results
 * */
class MyRunnable implements Runnable{
	private int ticketNum = 10;
	public void run() {
		while(this.ticketNum > 0) {
			System.out.println("Name: "+Thread.currentThread().getName()+" The remaining votes of the child thread: "+this.ticketNum);
			ticketNum--;
		}
	}	
}
public class MoreThread4_25{
	public static void main(String[] args) {
		MyRunnable myRunnable = new MyRunnable();
		Thread thread1 = new Thread(myRunnable,"A");
		Thread thread2 = new Thread(myRunnable,"B");
		Thread thread3 = new Thread(myRunnable,"C");
		thread1.start();	
		thread2.start();	
		thread3.start();	
	}
}

2. There is a pile of peaches on the beach, and five monkeys will divide it. The first monkey divided the pile of peaches into five equal parts, one more, the monkey threw the more one into the sea and took one. The second monkey divided the remaining peaches into five equal parts, and added one more. It also threw the extra peaches into the sea and took one part. The third, fourth, and fifth monkeys did the same. Yes, how many peaches were there at least on the beach?

public class MoreThread4_25{
	public static void main(String[] args) {
		// total number of records
		int total = 0;
		//Record the total number of peaches
		int peachNum = 1;//Suppose there is one peach left in each serving at the end
		boolean flag = false;
		while(!flag) {
			for(int i = 0;i <4;i++) {
				if(i == 0) {
					total = peachNum * 5 + 1;
				}
				//After each monkey takes one-fifth, the remaining peaches are multiples of 4
				if(total % 4 == 0) {
					total = (total/4)*5 + 1;
					if(i == 3) {
						flag = true;
					}
				}else {
					break;
				}
			}
			peachNum ++;
		}
		System.out.println("The fifth monkey took it: "+peachNum--);
		System.out.println("Total number of peaches: "+total);
	}
}








Guess you like

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