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);

    }
    }
    }

  • 相关阅读:
    C函数
    iOS开发- 蓝牙后台接收数据(BLE4.0)
    相册权限 第一次安装、用户是否授权
    使用免费的产品搭建直播系统
    搭建HTTP Live Streaming直播系统
    HTTP Live Streaming直播(iOS直播)技术分析与实现
    个人工作总结03
    个人工作总结02
    个人工作总结01
    第七周学习进度
  • 原文地址:https://www.cnblogs.com/lipu12281/p/12201499.html
Copyright © 2011-2022 走看看