zoukankan      html  css  js  c++  java
  • 线程礼让yield和线程的强制执行join

    少废话,直接看例子:

    注意礼让不一定都成功。

    关于yield的使用方式,例子如下:

    package com.lipu.state;
    
    public class TestYield {
        public static void main(String[] args) {
            MyYield myYield = new MyYield();
            new Thread(myYield,"a").start();
            new Thread(myYield,"b").start();
        }
    
    }
    class MyYield implements Runnable{
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"线程开始执行");
            Thread.yield();//礼让
            System.out.println(Thread.currentThread().getName()+"线程停止");
        }
    }

    关于join的使用方式,例子如下:

    package com.lipu.state;
    //测试join方法
    public class TestJoin implements Runnable {
        @Override
        public void run(){
            for (int i = 0; i < 10; i++) {
                System.out.println("线程VIP来了");
            }
        }
        public static void main(String[] args) throws InterruptedException {
            
            //启动我们的线程
            TestJoin testJoin = new TestJoin();
            Thread thread = new Thread(testJoin);
            thread.start();
            //主线程
            for (int i = 0; i < 100; i++) {
                if (i==20){
                    thread.join();//插队
                }
                System.out.println("main"+i);
                
            }
        }
    }

    输出结果:

     使用join线程会被强制插入

    package com.lipu.state;
    //测试join方法
    public class TestJoin implements Runnable {
    @Override
    public void run(){
    for (int i = 0; i < 10; i++) {
    System.out.println("线程VIP来了");
    }
    }
    public static void main(String[] args) throws InterruptedException {

    //启动线
    TestJoin testJoin = new TestJoin();
    Thread thread = new Thread(testJoin);
    thread.start();
    //线
    for (int i = 0; i < 100; i++) {
    if (i==20){
    thread.join();//插队
    }
    System.out.println("main"+i);

    }
    }
    }

  • 相关阅读:
    Firefox+BurpSuite绕过HSTS抓包
    如何在百万行代码中发现隐藏的后门
    10款常见的Webshell检测工具
    真实揭露:一段激情.视频裸.聊被骗的经历
    Kerberos速查表:如何攻击Kerberos
    在线播放视频加密/PDF电子书在线加密
    私人珍藏:WAF攻防实战笔记
    渗透利器 | 提权辅助工具箱
    这些年,我们一直追逐的漏洞利用神器
    如何防止CDN防护被绕过
  • 原文地址:https://www.cnblogs.com/lipu12281/p/12201499.html
Copyright © 2011-2022 走看看