public class JiOuTest {
public static void main(String[] args) {
PrintThread p=new PrintThread();
Thread t1=new Thread(p);
Thread t2=new Thread(p);
t1.start();
t2.start();
}
}
// 类锁
class PrintThread implements Runnable {
private static Object lock = new Object();
private static int num = 0;
@Override
public void run() {
synchronized (lock) {
while (num < 100) {
System.out.println(Thread.currentThread().getName() + "打印:" + ++num);
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
方法二:生产者消费者模式
需要注意的是:
不能是以Integer为共享对象,因为等等调用wait、notify需要是同一个对象,而integer++后变了
wait() notify() 需要是以java对象的方法,不是线程的方法
i.wait(); // 不能是直接wait()
i.notify() // 唤醒wait方法
public class ProductCustomer_jiou {
public static void main(String[] args) {
Num01 i=new Num01(1);
Thread t1=new Thread(new Ji(i));
Thread t2=new Thread(new Ou(i));
t1.start();
t2.start();
}
}
class Num01{
Integer num;
public Num01(Integer i){
this.num=i;
}
}
class Ji implements Runnable{
Num01 i;
public Ji(Num01 i){
this.i=i;
}
@Override
public void run(){
while(i.num<100){
synchronized(i){
if(i.num%2==0){
try{
i.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" "+i.num);
i.num++;
i.notify();
}
}
}
}
class Ou implements Runnable{
Num01 i;
public Ou(Num01 i){
this.i=i;
}
@Override
public void run(){
while(i.num<100){
synchronized(i){
if(i.num%2==1){
try{
i.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" "+i.num);
i.num++;
i.notify();
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)