Java多线程系列二之细谈Thread类

构造方法有

    • Constructor and Description
      Thread()

      Allocates a new Thread object.

      Thread(Runnable target)

      Allocates a new Thread object.

      Thread(Runnable target, String name)

      Allocates a new Thread object.

      Thread(String name)

      Allocates a new Thread object.

      Thread(ThreadGroup group, Runnable target)

      Allocates a new Thread object.

      Thread(ThreadGroup group, Runnable target, String name)

      Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

      Thread(ThreadGroup group, Runnable target, String name, long stackSize)

      Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

      Thread(ThreadGroup group, String name)

      Allocates a new Thread object.

说一下ThreadGroup,现在基本不用了,以前用的原因大多数是为了处理不受检异常,后来Thread类新增的方法就可以解决,所以基本废弃,能不用就不用

  • 线程组ThreadGroup对象中的stop,resume,suspend会导致安全问题,主要是死锁问题,已经被官方废弃,所以价值已经大不如以前。
  • 线程组ThreadGroup不是线程安全的,在使用过程中不能及时获取安全的信息。

Thread中主要用到的方法

    • static intactiveCount()

      Returns an estimate of the number of active threads in the current thread's thread group and its subgroups.

       

      • 返回当前线程的线程组中活动的线程数

       

    • voidcheckAccess()

      Determines if the currently running thread has permission to modify this thread.

      判断当前线程是否有权修改该线程

    • static ThreadcurrentThread()

      Returns a reference to the currently executing thread object.

      返回当前正在运行的线程的引用

 

    • static voiddumpStack()

      Prints a stack trace of the current thread to the standard error stream.

      将当前线程的堆栈跟踪信息打印至标准错误流

    • static intenumerate(Thread[] tarray)

      Copies into the specified array every active thread in the current thread's thread group and its subgroups.

      将当前线程的线程组及其子组中的每一个活动线程复制到指定的数组中

 

 

    • longgetId()

      Returns the identifier of this Thread.

      返回该线程的标识符

      StringgetName()

      Returns this thread's name.

      返回线程的名称

      intgetPriority()

      Returns this thread's priority.

      返回该线程的优先级

    • voidsetName(String name)

      Changes the name of this thread to be equal to the argument name.

      设置线程名

      voidsetPriority(int newPriority)

      Changes the priority of this thread.

      设置线程优先级

      voidsetUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)

      Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

      设置该线程由于未捕获异常而突然终止时调用的处理器

 

    • static voidsleep(long millis)

      Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

      设定当前线程在指定的时间内暂停执行

       

 

    • static voidsleep(long millis, int nanos)

      Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.

      与上类似

    • voidrun()

      If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

      如果该线程是使用独立的Runnable运行对象构建的,则调用该Runnable对象的run()方法;否则,该方法不执行任何操作并返回

      voidsetContextClassLoader(ClassLoader cl)

      Sets the context ClassLoader for this Thread.

      设置该线程的上下文ClassLoader

      voidsetDaemon(boolean on)

      Marks this thread as either a daemon thread or a user thread.

      标记该线程是守护线程还是用户线程

 

    • voidstart()

      Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

      启动线程

 

    • void

      stop()

      停止线程,不推荐使用,线程不安全

    • static voidyield()

      A hint to the scheduler that the current thread is willing to yield its current use of a processor.

      暂停执行当前正在运行的线程,并执行其他线程,不推荐使用

 

    • voidinterrupt()

      Interrupts this thread.

      中断该线程

      static booleaninterrupted()

      Tests whether the current thread has been interrupted.

      测试当前线程是否已经中断,如果中断就清除它的中断状态

 

    • booleanisInterrupted()

      Tests whether this thread has been interrupted.

      测试该线程是否中断,不影响线程状态

    • voidjoin()

      Waits for this thread to die.

      等待该线程终止

      voidjoin(long millis)

      Waits at most millis milliseconds for this thread to die.

      最多等待该线程在millis时间内终止

      voidjoin(long millis, int nanos)

      Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

      最多等待该线程在millis+nanos时间内终止

 

    • booleanisAlive()

      Tests if this thread is alive.

      检查该线程活动转台

 

    • static booleanholdsLock(Object obj)

      Returns true if and only if the current thread holds the monitor lock on the specified object.

      当且仅当当前线程在指定对象上保持监视器锁时返回true

 

import java.util.concurrent.Callable;
public class ThirdThread implements Callable<String>{
public String call() throws Exception{
try{
Thread.sleep(500L);
}catch(InterruptedException e){
e.printStackTrace();
}
Thread current=Thread.currentThread();
String name=current.getName();
System.out.println("当前线程名:"+name);
System.out.println("当前线程所属线程组活动线程数:"+Thread.activeCount());
System.out.println("当前线程标识符:"+current.getId());
System.out.println("当前线程状态:"+current.getState());
System.out.println("当前线程所属线程组:"+current.getThreadGroup());
System.out.println("当前线程是否处于活跃状态:"+current.isAlive());
System.out.println("当前线程是否为守护线程:"+current.isDaemon());

return "thread B";
}
}

 

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Test{
public static void main(String[] args){
ThirdThread thread=new ThirdThread();
System.out.println("Hello you");
FutureTask<String> feature=new FutureTask<String>(thread);
System.out.println("Hello he");
new Thread(feature).start();
System.out.println("This is Main Thread");
try{
System.out.println("the result from return"+feature.get());//该方法会阻塞直到得到返回结果
System.out.println("Hello lolo");
}catch(InterruptedException e){
e.printStackTrace();
}catch(ExecutionException e){
e.printStackTrace();
}
System.out.println("This is Main Thread:nd!");
}
}

 Thread使用时的注意事项如下:

(1)开启一个新的线程的时候,一定要给它一个名字,方便跟踪观察线程,对号入座,方便排查问题。

(2)需要注意的是,resume,stop,suspend等方法已经被废除,不建议使用,建议使用信号量(共享变量)或interrupt方法来代替stop方法等。

(3)main方法主线程结束了,新开启的子线程不一定结束

关于线程的中断机制

(1)Thread.stop().不安全,已不再建议使用,所以不说这个。

(2)利用Thread.interrupt()方法和机制

 

    • voidinterrupt()

      Interrupts this thread.

      中断线程,但没有返回结果,是唯一能将中断状态设置为true的方法

      static booleaninterrupted()

      Tests whether the current thread has been interrupted.

      测试当前线程是否已经中断,如果中断,就清除它的中断状态

    • booleanisInterrupted()

      Tests whether this thread has been interrupted.

      测试线程是否已经中断,线程的状态不受影响

 用个例子说明一下

 public class TestInterruptDemo{
public static void main(String[] args){
Thread thread=new Thread(()->
{
try{
Thread.sleep(10L);
System.out.println("learning feels well");
}catch(InterruptedException e){
e.printStackTrace();
}
},"test");
thread.start();
System.out.println("hello people");
System.out.println("线程test的中断状态:"+thread.isInterrupted());
//thread.interrupt();
//System.out.println("线程test的中断状态:"+thread.isInterrupted());
//在调用Thread.sleep(10L)期间如果再调用thread.interrupt()方法就报错。
Thread.interrupted();
System.out.println("线程test的中断状态:"+thread.isInterrupted());
System.out.println("hello everyone");
}
}

运行结果

线程常用方法再讲

守护线程

    • voidsetDaemon(boolean on)

      Marks this thread as either a daemon thread or a user thread.

 

改一下之前的代码,加入 thread.setDaemon(true);读者自行比较一下运行结果

 public class TestInterruptDemo{
public static void main(String[] args){
Thread thread=new Thread(()->
{
try{
Thread.sleep(10L);
System.out.println("learning feels well");
}catch(InterruptedException e){
e.printStackTrace();
}
},"test");
thread.setDaemon(true);
thread.start();
System.out.println("hello people");
System.out.println("线程test的中断状态:"+thread.isInterrupted());
//thread.interrupt();
//System.out.println("线程test的中断状态:"+thread.isInterrupted());
//在调用Thread.sleep(10L)期间如果再调用thread.interrupt()方法就报错。
Thread.interrupted();
System.out.println("线程test的中断状态:"+thread.isInterrupted());
System.out.println("hello everyone");
System.out.println("线程test的中断状态:"+thread.isInterrupted());
}
}

运行结果

线程组

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值