栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

两个线程交替输出1-100

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

两个线程交替输出1-100

两个线程交替输出1-100 方法一:使用类锁
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();
            }
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862776.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号