Java多线程Thread常用方法
Posted xianya
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程Thread常用方法相关的知识,希望对你有一定的参考价值。
- 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常用方法的主要内容,如果未能解决你的问题,请参考以下文章