码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程Thread常用方法

时间:2018-06-17 19:00:11      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:class   rri   执行   extends   star   set   static   停止   ati   

  • getName():获取此线程的名字
  • setName():设置此线程的名字
  • currentThread():静态的,调取当前的线程
  • run():子线程要执行的代码放入run()方法中
  • start():启动线程并执行相应的run()方法
package com.yyx.test;

public class TestThread {
    public static void main(String[] args) {
        ThreadDemo thread1 = new ThreadDemo();
        thread1.setName("线程一");
        ThreadDemo thread2 = new ThreadDemo();
        thread2.setName("线程二");
        thread1.start();
        thread2.start();
    }
}

class ThreadDemo extends Thread {

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }

}
  •  join():在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直至B线程执行完毕
  •  sleep(long l):显式的让当前线程睡眠l毫秒
package com.yyx.test;

public class TestThread {
    public static void main(String[] args) {
        ThreadDemo thread = new ThreadDemo();
        thread.setName("线程一");
        thread.start();
        for(int j=1;j<=20;j++) {
            Thread.currentThread().setName("主线程");
            System.out.println(Thread.currentThread().getName() + ":" + j);
            if(j==10) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }                
            }
            
        }
    }
}

class ThreadDemo extends Thread {

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

 

Java多线程Thread常用方法

标签:class   rri   执行   extends   star   set   static   停止   ati   

原文地址:https://www.cnblogs.com/xianya/p/9192941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!