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

     线程的常用方法基本都在Thread类中,所以大部分都是通过Thread类进行调用的

    1.取得当前线程的名称:

      getName()

    2.取得当前线程对象:

      currentThread()

    3.判断线程是否启动:

      isAlive()

    4.线程的强行运行:

      join()

    5.线程的休眠

      sleep()

    6.线程的礼让(针对生命周期是非常重要的 )

      yield()
    =============================================================

    ThreadDemo03.java

     线程未启动之前是false,启动之后是true

     

    当主线程执行到10的时候,自己的线程开始执行,执行完毕后将cpu资源让给主线程

    package thread;

    class RunnableDemo implements Runnable{

    private String name;
    //创建构造方法,以标识当前哪一个线程执行
    public RunnableDemo(String name) {
    this.name=name;
    }

    @Override
    public void run() {
    for (int i = 0; i < 50; i++) {
    try {
    //线程休眠1秒钟
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    //System.out.println("当前线程对象:"+Thread.currentThread().getName());
    System.out.println(name+":"+i);
    }
    }
    }
    public class ThreadDemo03 {
    public static void main(String[] args) {
    //实例化线程对象
    RunnableDemo r1=new RunnableDemo("A");
    //RunnableDemo r2=new RunnableDemo("B");

    Thread t1=new Thread(r1);
    //判断线程是否启动,
    //System.out.println(t1.isAlive());
    //Thread t2=new Thread(r2);
    t1.start();
    //t2.start();
    //启动之后再来判断
    //System.out.println(t1.isAlive());
    for (int i = 0; i < 50; i++) {
    if(i>10) {
    try {
    t1.join();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("主线程:"+i);
    }
    }
    }

    =========================================================

    线程的礼让

    package thread;

    class RunnableDemo implements Runnable{

    private String name;
    //创建构造方法,以标识当前哪一个线程执行
    public RunnableDemo(String name) {
    this.name=name;
    }

    @Override
    public void run() {
    for (int i = 0; i < 50; i++) {
    System.out.println(name+":"+i);
    if (i==10) {
    System.out.println("礼让");
    Thread.yield();
    }
    }
    }
    }
    public class ThreadDemo03 {
    public static void main(String[] args) {
    //实例化线程对象
    RunnableDemo r1=new RunnableDemo("A");
    RunnableDemo r2=new RunnableDemo("B");

    Thread t1=new Thread(r1);
    Thread t2=new Thread(r2);
    t1.start();
    t2.start();

    }
    }

  • 相关阅读:
    Codeforces Round #649 (Div. 2) D. Ehab's Last Corollary
    Educational Codeforces Round 89 (Rated for Div. 2) E. Two Arrays
    Educational Codeforces Round 89 (Rated for Div. 2) D. Two Divisors
    Codeforces Round #647 (Div. 2) E. Johnny and Grandmaster
    Codeforces Round #647 (Div. 2) F. Johnny and Megan's Necklace
    Codeforces Round #648 (Div. 2) G. Secure Password
    Codeforces Round #646 (Div. 2) F. Rotating Substrings
    C++STL常见用法
    各类学习慕课(不定期更新
    高阶等差数列
  • 原文地址:https://www.cnblogs.com/curedfisher/p/11975233.html
Copyright © 2011-2022 走看看