package com.jokin.learn.Jdk18;
/**
* java实现两个线程交替打印0-99
* https://blog.youkuaiyun.com/dadiyang/article/details/88315124
*/
public class TwoThreadPrint0_99_2 {
private static int count = 0;
private static final Object lock = new Object();
/**
* 见类上面的备注
* @param args
*/
public static void main(String[] args) {
Thread even = new Thread(() -> {
while (count <= 100) {
synchronized (lock) {
System.out.println("偶数: " + count++);
lock.notifyAll();// 唤醒其他线程
try {
// 如果还没有结束,则让出当前的锁并休眠
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread odd = new Thread(() -> {
while (count <= 100) {
synchronized (lock) {
System.out.println("奇数: " + count++);
lock.notifyAll();// 唤醒其他线程
try {
// 如果还没有结束,则让出当前的锁并休眠
if (count <= 100) {
lock.wait();//当线程执行wait()方法时候,会释放当前的锁,然后让出CPU,进入等待状态使当前线程阻塞
//只有当 notify/notifyAll() 被执行时候,才会唤醒一个或多个正处于等待状态的线程,然后继续往下执行,直到执行完synchronized 代码块的代码或是中途遇到wait() ,再次释放锁
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
even.start();
// 确保偶数线程线先获取到锁
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
odd.start();
}
}
方法二(不推荐,因为low线程阻塞):
package com.jokin.learn.Jdk18;
import java.util.Comparator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* java实现两个线程交替打印0-99
* https://blog.youkuaiyun.com/dadiyang/article/details/88315124
*/
public class TwoThreadPrint0_99 {
private static int count = 0;
private static final Object lock = new Object();
/**
* 见类上面的备注
* @param args
*/
public static void main(String[] args) {
Thread a = new Thread();
a.start();
System.out.println("当前线程id;"+a.getId()+" " + a.getName());
System.out.println("当前线程id;"+Thread.currentThread().getId()+" " + Thread.currentThread().getName());
// public Thread(Runnable target, String name)
//public Thread(Runnable target)
Thread even = new Thread(()->{
while (count < 100) {
synchronized (lock) {
// 只处理偶数
if ((count & 1) == 0) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
}
}
}},"偶数"
);
Thread odd = new Thread(() -> {
while (count < 100) {
synchronized (lock) {
// 只处理奇数
if ((count & 1) == 1) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
}
}
}
}, "奇数");
even.start();
odd.start();
}
}