多线程常用api

常用线程api方法

start() 启动线程
currentThread() 获取当前线程对象
getID() 获取当前线程ID Thread-编号 该编号从0开始
getName() 获取当前线程名称
sleep(long mill) 休眠线程
Stop() 停止线程,

常用线程构造函数
Thread() 分配一个新的 Thread 对象
Thread(String name) 分配一个新的 Thread对象,具有指定的 name正如其名。
Thread(Runable r) 分配一个新的 Thread对象
Thread(Runable r, String name) 分配一个新的 Thread对象

具体代码如下:

package com.newDemo.controller.test;

class CreateThreadDemo04 extends Thread{
	/**
	 * run方法就是线程需要执行的任务或者执行的代码
	 */
	@Override
	public void run() {
		for (int i = 0; i < 30; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("子线程id:" + getId() + ":子线程 ,i:" + i + "name:" + getName());
			System.out.println("子线程id:" + Thread.currentThread().getId() + ",name:" + Thread.currentThread().getName());
			 if(i==5){
		    	 Thread.currentThread().stop();// 不安全。不建议大家使用。
		    }
		}

	}
}

public class threadDemo4 {
	public static void main(String[] args) {
		// 1. 怎么调用线程
		CreateThreadDemo04 t1 = new CreateThreadDemo04();
		// 2.启动线程 不是调用run方法,而是调用start方法。
		// 3.使用开启多线程后,代码不会从上往下进行执行。
		t1.start();
		System.out.println("主线程:" + Thread.currentThread().getId() + ",name:" + Thread.currentThread().getName());
//		Thread.currentThread()获取到当前线程的
//		for (int i = 0; i < 30; i++) {
//			System.out.println("main,i:" + i);
//		}
		CreateThreadDemo04 t2 = new CreateThreadDemo04();
		Thread thread = new Thread(t1, "子线程");
		thread.start();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值