最重要的就是两个线程 公用一把锁 这点如果不是一把锁 就达不到效果
最重要的就是两个线程 公用一把锁 这点如果不是一把锁 就达不到效果
最重要的就是两个线程 公用一把锁 这点如果不是一把锁 就达不到效果
我这里就弄了一个obj作为两个线程的监视器
package com.oneday.dierci;
public class jioushu {
public static void main(String[] args) {
Object obj = new Object();
jishu jishu = new jishu(obj);
oushu oushu = new oushu(obj);
Thread thread1 = new Thread(jishu);
Thread thread2 = new Thread(oushu);
thread1.setName("基数线程");
thread2.setName("偶数线程");
thread2.start();
thread1.start();
}
}
class jishu implements Runnable{
Object obj;
public jishu(Object obj) {
this.obj = obj;
}
@Override
public void run() {
synchronized(obj) {
for (int i =0 ; i < 100 ; i ++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + "输出奇数" + i);
obj.notify();
try {
obj.wait();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class oushu implements Runnable{
Object obj;
public oushu(Object obj) {
this.obj = obj;
}
@Override
public void run() {
synchronized (obj){
for (int i =0 ; i < 100 ; i ++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + "输出偶数" + i);
obj.notify();
try {
obj.wait();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}