//使用Runnable接口创建三个子线程并起名为A,B,C模拟实现卖票操作,观察结果。 class MyThread implements Runnable{ private int tickets = 20; //方法1:使用sychronized(this){}块 // @Override // public void run() { // while(tickets>0) { // synchronized(this) { // if(tickets>0) { // System.out.println(Thread.currentThread().getName()+": "+tickets-- +"票"); // } // } // } // } //方法2:sychronized方法 @Override public void run() { while(tickets>0) { this.sale(); } } public synchronized void sale() { if(tickets>0) { try { Thread.sleep(50); System.out.println(Thread.currentThread().getName()+": "+tickets-- +"票"); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Test26 { public static void main(String[] args) { MyThread mythread = new MyThread(); Thread th1 = new Thread(mythread, "窗口A"); Thread th2 = new Thread(mythread, "窗口B"); Thread th3 = new Thread(mythread, "窗口C"); th1.start(); th2.start(); th3.start(); } }
(算法)题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
第一眼看到这道题以为很简单,想直接做一个五次循环倒序算桃子数量就可以了,结果入坑了!!!
这道题想要靠自己在本子上举出例子都不太现实,因为答案最小的桃子数量是3121,这道题需要穷举,直到找到符合条件的值!
分析:每一次,猴子分5份桃子都会多出一个,自己再拿走一份,也就是说桃子满足以下条件:
(桃子数量-1)%5==0, 剩下桃子数量=(桃子数量-1)/5*4
public class Test262 { public static void main(String[] args) { for(int i=1;i<10000;i++) { if(taozi(i)) { System.out.println(i); } } } public static boolean taozi(int n) { for(int i=0;i<5;i++) { n--; if(n%5!=0) { return false; } n=n/5*4; } return true; } }
运行结果
一万以内符合条件的桃子数量:
3121
6246
9371