Java 面试题 线程打印奇偶
public class ThreadDome2 {
static int i =0;
public static void main(String[] args) {
Object o = new Object();
new Thread(()->{
String name = Thread.currentThread().getName();
while (i<100){
synchronized (o){
if( i % 2 ==0){
System.out.println(name+":"+i);
}
i++;
o.notify();
try {
if(i==100){
Thread.currentThread().interrupt();
}else{
o.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"偶数").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
String name = Thread.currentThread().getName();
while (i<100){
synchronized (o){
if( i % 2 ==1){
System.out.println(name+":"+i);
}
i++;
o.notify();
try {
if(i==100){
Thread.currentThread().interrupt();
}else{
o.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"奇数").start();
}
}
Java 简易生产者消费者
public class ThreadDome3 {
static Object o = new Object();
static LinkedList<String> list = new LinkedList<>();
static int max = 10;
// 产
public static void put(){
while (true){
synchronized (o){
if(list !=null && list.size() == max){
System.out.println("生产进入阻塞");
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
while (list.size()<max){
list.add("面包");
System.out.println("生产者生产面包");
}
o.notify();
}
}
}
}
// 消
public static void task(){
while (true){
synchronized (o){
if(list !=null && list.size()>0){
for (int i =0; i < list.size(); i++){
System.out.println("消费者消费"+ list.get(i));
}
list.clear();
o.notify();
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new Thread(()->{ put();}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{ task();}).start();
}
Java 反转数组
Java 简易LRU