• 线程同步


    同步 就像食堂排队取餐一样,前面一个人取完餐 后面的人才可以继续取餐 ,线程同步和异步与字面意思正好相反 同步就是有先后顺序  一段代码执行后才会执行另一端代码,而线程异步则是 多个代码块同时执行 没有顺序之分

    //继承Thread
    public class MyHread1 extends Thread {
    public Print p1;

    @Override
    public void run() {
    //循环打印print1中的内容
    for (int i = 1; i <= 5; i++) {
    p1.print1();

    }




    }


    }

    复制代码
    public class MyThread2 implements Runnable{
    public Print p1;
        @Override
        public void run() {
              //循环输出print2中的内容
            for (int i = 1; i <= 5; i++) {
                p1.print2();
                
            }
        }
    
    }
    复制代码

    定义两个类  一个继承Thread 另一个实现Runable  循环输出内容  分别在void前加上锁synchronized

    复制代码
    public class Print {
    
    
        public synchronized void print1(){
            
            System.out.print("我");
            System.out.print("是");
            
            System.out.println();
        }
        
        public synchronized void print2(){
            
            System.out.print("好");
            System.out.print("人");
            System.out.println();
            
        }
    
    }
    复制代码

    定义一个print类  类中有两个方法 分别输出内容  并且内容之间不换行  直至全部结束再换行

    复制代码
    public class Test {
        
        public static void main(String[] args) {
            MyHread1 mh=new MyHread1();
            Print p=new Print();
            mh.p1=p;
            
            mh.start();
            
            
            MyThread2 mh2=new MyThread2();
            
            mh2.p1=p;
            Thread th=new Thread(mh2);
            
            th.start();
            
        }
    
    }


    复制代码

    运行结果如下:

  • 相关阅读:
    Docker
    Dotted lines by default in ViVA
    8245H(C2)光猫配置方法
    两种将verilog网表转为spice网表的方法
    calibredrv create reference cell
    怎么flatten一个GDS所有层次
    路由器后面访问光猫
    贝尔IPTV
    PDK导出的cdl MOS四端顺序不正确
    如何删除已经存在lib的techfile
  • 原文地址:https://www.cnblogs.com/superws/p/5770604.html
Copyright © 2020-2023  润新知