zoukankan      html  css  js  c++  java
  • (Java)线程的强制运行和线程的休眠

    一、线程的强制运行

    二、线程的休眠

    一、线程的强制运行

    在线程操作中,可以使用 join() 方法让一个线程强制运行,线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行

    class MyThread implements Runnable{//实现 Runnable 接口

        public void run(){//覆写 Thread 类中的 run() 方法

            for(int i=0;i<5;i++){

                System.out.println(Thread.currentThread().getName()

                + "运行 --> " + i);//取得当前线程的名称

            }

        }

    }

    public class Root{

        public static void main(String[] args) {

            MyThread my = new MyThread();//定义 Runnable 子类对象

            Thread t = new Thread(my,"线程");//实例化 Thread 对象

            t.start();//启动线程

            for(int i=0;i<6;i++){

                if(i>2){

                    try {

                        t.join();//线程 t 进行强制运行

                    }catch (Exception e){}//需要进行异常处理

                }

                System.out.println("Main 线程运行 --> " + i);

            }

        }

    }

    二、线程的休眠

    在程序中允许一个线程进行暂时的休眠,直接使用 Thread.sleep() 方法即可实现休眠

    class MyThread implements Runnable{//实现 Runnable 接口

        public void run(){//覆写 Thread 类中的 run() 方法

            for(int i=0;i<5;i++){

                try{

                    Thread.sleep(2);//线程休眠

                }catch (Exception e){}

                System.out.println(Thread.currentThread().getName()

                + "运行 --> " + i);//取得当前线程的名称

            }

        }

    }

    public class Root{

        public static void main(String[] args) {

            MyThread my = new MyThread();//定义 Runnable 子类对象

            Thread t = new Thread(my,"线程");//实例化 Thread 对象

            t.start();//启动线程

        }

    }

  • 相关阅读:
    python 编码 整理总结
    搜索目录下 匹配文件中 最新的文件 路径
    DIV+CSS实现页面居中
    反射怎样调用另外一个类的私有成员
    ASP.NET中路径相关的一些问题
    相对定位以及父子节点之间的关系
    C#垃圾回收机制
    javascript和html中关于自定义属性的问题
    在C#中使用指针(哈哈,炫吧!)
    jquery中过滤器的应用,实现QQ的TAB效果
  • 原文地址:https://www.cnblogs.com/zhuyeshen/p/12708652.html
Copyright © 2011-2022 走看看