34. Thread类的常用方法
2024-10-07 18:46:14
1.构造方法
Thread()
分配新的
Thread
对象。
Thread(String name) 分配新的 Thread
对象并指定线程名字
2.方法
1)setName(String name) 设置线程的名字
public final void setName(String name)
2)getName() 获取线程名字
public final String getName()
public static void main(String[] args) {
Thread thread = new Thread("狗娃");
System.out.println(thread.getName());;
thread.setName("张三");
System.out.println(thread.getName());;
}
3)sleep() 指定线程睡眠的时间,单位毫秒(注意:谁执行了sleep代码,谁睡眠,并不是谁调用了sleep方法谁睡眠)
public static void sleep(long millis,int nanos)
throws InterruptedException
class sonThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是自定义线程");
}
}
} public class Demo3 {
public static void main(String[] args) { sonThread sonthread = new sonThread();
sonthread.start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
System.out.println("我是main线程");
}
}
}
注意:sleep代码是main线程执行的,所以main线程随眠200毫秒
4)currentThread() 返回执行此代码的对象(注意:跟sleep一样是执行此代码,而不是调用)
public static Thread currentThread()
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
5)getPriority() 返回当前线程对象的优先级(默认为5,优先级在1-10之间)
6)setPriority() 设置当前线程对象的优先级(默认为5,优先级在1-10之间)
public static void main(String[] args) {
Thread thread = new Thread("狗娃");
System.out.println("默认的优先级是:"+thread.getPriority());
thread.setPriority(7);
System.out.println("现在的优先级是:"+thread.getPriority());
}
最新文章
- C#使用 DirectX SDK 9做视频播放器 并在视频画线添加文字 VMR9
- 黑马程序员_Java基础:序列化(Serializable)与反序列化
- C/C++关于string.h头文件和string类
- CSS之CSS hack
- apt-get的常用用法
- SRM 584 第一次玩TopCoder。。。只水题一道。。。
- MVC3、如何应用EntityFramework 连接MySql 数据库
- jQuery each的实现与call方法的详细介绍
- servlet案例
- HDU 1166 敌兵布阵 线段树区间求和 更改
- Android M(6.0) 权限爬坑之旅
- 电脑安装win8.1后 前面板没有声音的解决办法
- mini-httpd源码分析-match.h
- 模式匹配KMP
- Mybatis中的like查询
- Cs231n课堂内容记录-Lecture 6 神经网络训练
- 安装SQL Server 2008时,安装程序配置检查RebootRequiredCheck时失败
- Redis进阶实践之五Redis的高级特性(转载 5)
- SharePoint PowerShell 修改计时器任务
- 删除排序数组中的重复数字 II