public class Main implements Runnable {
private Integer num;
private Object lock;
public Main(Integer num, Object lock) {
this.num = num;
this.lock = lock;
}
public static void main(String[] args) {
Object lock = new Object();
Thread thread1 = new Thread(new Main(1, lock));
Thread thread2 = new Thread(new Main(2, lock));
thread1.start();
thread2.start();
}//main
@Override
public void run() {
while (true) {
synchronized (lock) {//得到锁
try {
lock.notify();//唤醒其他的线程,交替唤醒
lock.wait();//自己等待,释放锁,交替等待
System.out.println(num+","+Thread.currentThread().getName());
Java多线程,交替输出121212
最新推荐文章于 2025-02-18 01:41:13 发布