• Thread.yield()方法表示交出主动权,join表示等待当前线程,可以指定秒数


    Thread.yield()方法表示交出主动权,join表示等待当前线程,可以指定秒数

    学习了:http://www.importnew.com/14958.html 膜拜一下

    源码膜拜:

    Thread.yield()没准,顺序输出不一定;

    package com.stono.thread;
    
    public class YieldExample {
        public static void main(String[] args) {
            Thread producer = new Producer();
            Thread consumer = new Consumer();
            producer.setPriority(Thread.MIN_PRIORITY);
            consumer.setPriority(Thread.MAX_PRIORITY);
            producer.start();
            consumer.start();
        }
    }
    
    class Producer extends Thread{
        @Override
        public void run() {
            for(int i=0;i<5;i++){
                System.out.println("I am Producer: Procuded Item ============="+ i);
                Thread.yield();
            }
        }
    }
    
    class Consumer extends Thread{
        @Override
        public void run() {
            for(int i=0;i<5;i++){
                System.out.println("I am consumer: Consumed Item "+i);
                Thread.yield();
            }
            
        }
    }

    Join表示要等待当前线程,可以指定等待的毫秒数;

    package com.stono.thread;
    
    import java.util.concurrent.TimeUnit;
    
    public class JoinExample {
        public static void main(String[] args) throws InterruptedException {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    System.out.println("First task started");
                    System.out.println("Sleeping for 2 seconds");
                    try {
                        //Thread.sleep(2000);
                        TimeUnit.SECONDS.sleep(2);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("First task complete");
                }
            });
            
            Thread t1 = new Thread(new Runnable() {
                public void run() {
                    System.out.println("Second task completed");
                }
            });
            
            t.start();
            t.join();
            // t.join(100); // 这个表示等待100毫秒
            t1.start();
        }
    }
  • 相关阅读:
    HDU
    hdu-1260 tickets
    hdu-1024 Max Sum Plus Plus
    spfa+链式前向星模板
    kafka-伪集群搭建
    elasticsearch-安装-centos7- es7.5 搭建
    elk-安装 通过docker
    kibana-安装-通过docker
    logstash -grok插件语法介绍
    docker 启动redis/nginx
  • 原文地址:https://www.cnblogs.com/stono/p/8341750.html
Copyright © 2020-2023  润新知