根据年月日获取日期数
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);
}
}
多线程哲学家进食问题
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);
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;
int dot = (leftFirst ? no - 1 : no);
if (dot == 0) dot = 5;
System.out.println(no + "拿到了吃饭卡,并且准备去拿" + (leftFirst ? "左边" : "右边") + "叉子=" + dot);
if (leftFirst) {
left.acquire();
} else {
right.acquire();
}
System.out.println(no + "拿到了" + (leftFirst ? "左边" : "右边") + "叉子=" + dot);
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 {
right.release();
left.release();
System.out.println(no + "释放了所有叉子");
forkControl.release();
System.out.println(no + "释放了吃饭卡");
System.out.println(this.no + "号哲学家在休息");
}
}
}
}