内容目录:
详细讲解Thread类中函数的作用和实例
正文:
Thread类,线程基础类,位于java.lang包下,现对Thread类进行详细讲解
函数:
static int activeCount() -- 返回当前线程所在ThreadGroup中的子线程的数量
例子:
package com.redis.chat;
public class Hello{
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("Admin Thread");
t.setPriority(Thread.MAX_PRIORITY);
System.out.println("Thread===>"+t);
int count = Thread.activeCount();
System.out.println("currently active threads = " + count);
}
}
结果:
Thread===>Thread[Admin Thread,10,main]
currently active threads = 1
分析:1、当前线程的名称为 Admin Thread , 优先级别为 10 , 主线程
2、当前线程所在的线程组中的线程有1个
void checkAccess() -- 当前线程是否有权限修改指定的线程,如果不允许访问则抛出SericurityException
例子:
package com.redis.chat;
public class Hello{
public static void main(String[] args) {
String tr1 = "孽徒,哪里走!";
Thread t1 = Thread.currentThread();
new SunWuKong(t1 , tr1);
try {
t1.checkAccess();
System.out.println("内容修改成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SunWuKong implements Runnable{
String tr = "你好,孙悟空!";
Thread th;
SunWuKong(Thread t1 , String name){
this.tr = name;
System.out.println(this.tr);
th = new Thread(t1);
th.start();
}
@Override
public void run() {
System.out.println(tr);
}
}
结果:
孽徒,哪里走!
内容修改成功
分析:
1、主线程修改了SunWuKong线程中的tr变量
Static Threa currentThread() -- 获取当前正在运行的线程
例子:
package com.redis.chat;
public class Hello{
public static void main(String[] args) {
Thread t1 = Thread.currentThread();
System.out.println(t1);
}
}
结果:
Thread[main,5,main]
分析:
1、获取当前线程的信息
Static void dumpStack() -- 获取当前线程的堆栈信息并打印到控制台,运用性能调试
例子:
public class Hello{
public static void main(String[] args) {
Thread t1 = Thread.currentThread();
t1.setName("admin main");
t1.setPriority(Thread.MIN_PRIORITY);
System.out.println("thread==>"+t1);
Thread.dumpStack();
}
}