Java每日一练11
根据年月日获取日期数
class Solution5 {
public String dayOfTheWeek(int day, int month, int year) {
LocalDate localDate = LocalDate.of(year, month, day);
String[] ss = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
return ss[localDate.getDayOfWeek().getValue() - 1];
}
}
class LocalDateTest {
public static void main(String[] args) {
Solution5 solution5 = new Solution5();
String s = solution5.dayOfTheWeek(3, 1, 2022);
System.out.println(s); // Monday
}
}
多线程哲学家进食问题
class DinnerExecutor {
static final Semaphore fork1 = new Semaphore(1);
static final Semaphore fork2 = new Semaphore(1);
static final Semaphore fork3 = new Semaphore(1);
static final Semaphore fork4 = new Semaphore(1);
static final Semaphore fork5 = new Semaphore(1);
// 防止死锁的发生,给了4个控制权
static final Semaphore forkControl = new Semaphore(4);
public static void main(String[] args) {
new Thread(new Philosopher(1, fork5, fork1)).start();
new Thread(new Philosopher(2, fork1, fork2)).start();
new Thread(new Philosopher(3, fork2, fork3)).start();
new Thread(new Philosopher(4, fork3, fork4)).start();
new Thread(new Philosopher(5, fork4, fork5)).start();
}
static class Philosopher implements Runnable {
int no; // 哲学家编号
Semaphore left; // 哲学家左边的叉子
Semaphore right; // 哲学家右边的叉子
public Philosopher(int no, Semaphore left, Semaphore right) {
this.no = no;
this.left = left;
this.right = right;
}
public void run() {
try {
// 这是饭卡许可证,为了防止死锁的发生,有一位哲学家得不到吃饭权
forkControl.acquire();
boolean leftFirst = new Random().nextInt(2) % 2 == 0; // true,false
// 计算叉子坐标
int dot = (leftFirst ? no - 1 : no); // no - 1左,no右
if (dot == 0) dot = 5; // 按顺时针放叉子的位置的话,坐标5就是编号为1哲学家叉子的左边
// 预分配叉子的使用权,剩下的全靠哲学家抢占时间片的速度来决定哪位哲学家拿到了叉子
System.out.println(no + "拿到了吃饭卡,并且准备去拿" + (leftFirst ? "左边" : "右边") + "叉子=" + dot);
if (leftFirst) {
left.acquire(); // 拿走叉子的使用权
} else {
right.acquire(); // 拿走叉子的使用权
}
System.out.println(no + "拿到了" + (leftFirst ? "左边" : "右边") + "叉子=" + dot);
// 线程sleep方法,下面抢占叉子的概率是等可能的
Thread.sleep(1000);
// 哲学家们再次枪占叉子
if (leftFirst) {
right.acquire();
} else {
left.acquire();
}
int dot2 = (leftFirst ? no : no - 1);
if (dot2 == 0) dot2 = 5;
System.out.println(no + "也拿到了另一边叉子=" + dot2);
System.out.println(this.no + "号哲学家在吃饭");
// 下一次抢占也是等可能的
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 程序运行到此处
// 一位哲学家成功进食并且放下了叉子
// 正常的话,这里一共会被执行5次
right.release();
left.release();
System.out.println(no + "释放了所有叉子");
forkControl.release();
System.out.println(no + "释放了吃饭卡");
System.out.println(this.no + "号哲学家在休息");
}
}
}
}