1、使用Runnable接口创建三个子线程并起名为A,B,C模拟实现卖票操作,观察结果
/* * 使用Runnable接口创建三个子线程并起名为A,B,C模拟实现卖票操作,观察结果 * */ class MyRunnable implements Runnable{ private int ticketNum = 10; public void run() { while(this.ticketNum > 0) { System.out.println("名为:"+Thread.currentThread().getName()+"的子线程剩余票数:"+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、海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
public class MoreThread4_25{ public static void main(String[] args) { //记录总数 int total = 0; //记录桃子总数 int peachNum = 1;//假设最后每一份中剩一个桃子 boolean flag = false; while(!flag) { for(int i = 0;i <4;i++) { if(i == 0) { total = peachNum * 5 + 1; } //每个猴子拿走五分之一后,剩下的桃子是4的倍数的情况 if(total % 4 == 0) { total = (total/4)*5 + 1; if(i == 3) { flag = true; } }else { break; } } peachNum++; } System.out.println("第五只猴子拿走了:"+peachNum--); System.out.println("桃子总数:"+total); } }