zoukankan      html  css  js  c++  java
  • 线程的常用方法

    -------------siwuxie095

       

       

       

       

       

       

    线程的常用方法基本都在 Thread 类中,Runnable 接口中只有一个 run() 抽象方法

       

    1)取得线程名称:getName()

       

    (2)取得当前线程对象:currentThread()

       

    (3)判断线程是否启动:isAlive()

       

    (4)线程的强行运行:join()

       

    (5)线程的休眠:sleep()

       

    (6)线程的礼让:yield()

       

       

       

       

       

    代码:

       

    package com.siwuxie095.thread;

       

       

    class MyRunnableX implements Runnable{

     

    private String name;

     

    //构造方法,传入参数 name,用于标识当前线程

    public MyRunnableX(String name) {

    this.name=name;

    }

     

     

    //复写 Runnable run()方法

    public void run() {

    //(1)打印当前线程名称

    //System.out.println("当前线程名称:"+Thread.currentThread().getName());

     

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

    // (2)线程休眠

    // try {

    // //设置休眠时间为1秒,即 1秒执行一次

    // //在打印 name-i 时,1秒打印一次,从视觉上看起来比较明显

    // Thread.sleep(1000);

    // } catch (InterruptedException e) {

    // e.printStackTrace();

    // }

     

    System.out.println(name+"-"+i);

     

    //(3)线程礼让

    if (i==5) {

    //当线程执行到5时进行礼让,另一个线程开始执行

    System.out.println("礼让:");

    Thread.yield();

    }

    }

    }

    }

       

       

    public class ThreadDemoX {

       

    public static void main(String[] args) {

    MyRunnableX r1=new MyRunnableX("A");

    MyRunnableX r2=new MyRunnableX("B");

    //Runnable创建的线程依赖于Thread启动

    Thread t1=new Thread(r1);

    Thread t2=new Thread(r2);

    //判断线程t1是否启动

    System.out.println("t1启动:"+t1.isAlive());

    t1.start();

    t2.start();

    System.out.println("t1启动:"+t1.isAlive());

    System.out.println("当前线程名称:"+Thread.currentThread().getName());

    System.out.println();

     

    //(4)线程强行执行

    //当主线程执行到10时,t1t2开始执行(强行),t1t2执行完毕,

    //之后再把CPU资源让给主线程继续执行

    // for (int i = 0; i < 20; i++) {

    // if (i>10) {

    //

    // try {

    // //如果i>10,强行执行t1t2线程

    // //需要加 try catch 捕获异常

    // t1.join();

    // t2.join();

    // } catch (InterruptedException e) {

    // e.printStackTrace();

    // }

    // }

    // System.out.println("主线程:"+i);

    // }

     

    }

       

    }

       

       

    运行一览:

       

    线程是否启动 当前线程名称:

       

       

       

       

    线程的强行运行:

       

     

       

       

     

    线程的礼让:

       

       

       

       

       

       

       

    【made by siwuxie095】

     

  • 相关阅读:
    Codeforces Round #604(Div. 2,
    简单的三层框架以及使用dbutils进行数据库操作(入门)
    DBUtil数据库工具封装
    GUI 中监听 文本框实时改变的实例
    java基础教程GUI
    Dao层通用化,Spring3.0+Hibernate3.3.2通用Dao层整合
    计算器代码
    记事本应用程序java源代码
    GUI
    dbutils开源项目用法
  • 原文地址:https://www.cnblogs.com/siwuxie095/p/6629106.html
Copyright © 2011-2022 走看看