java 大道至简--多线程(3)

 java 大道至简--多线程(3)

内容目录:

  详细讲解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();
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值