构造方法有
Constructor and Description |
---|
Thread() Allocates a new |
Thread(Runnable target) Allocates a new |
Thread(Runnable target, String name) Allocates a new |
Thread(String name) Allocates a new |
Thread(ThreadGroup group, Runnable target) Allocates a new |
Thread(ThreadGroup group, Runnable target, String name) Allocates a new |
Thread(ThreadGroup group, Runnable target, String name, long stackSize) Allocates a new |
Thread(ThreadGroup group, String name) Allocates a new |
说一下ThreadGroup,现在基本不用了,以前用的原因大多数是为了处理不受检异常,后来Thread类新增的方法就可以解决,所以基本废弃,能不用就不用
Thread中主要用到的方法
static int |
activeCount() Returns an estimate of the number of active threads in the current thread's thread group and its subgroups.
|
void |
checkAccess() Determines if the currently running thread has permission to modify this thread. 判断当前线程是否有权修改该线程 |
static Thread |
currentThread() Returns a reference to the currently executing thread object. 返回当前正在运行的线程的引用 |
static void |
dumpStack() Prints a stack trace of the current thread to the standard error stream. 将当前线程的堆栈跟踪信息打印至标准错误流 |
static int |
enumerate(Thread[] tarray) Copies into the specified array every active thread in the current thread's thread group and its subgroups. 将当前线程的线程组及其子组中的每一个活动线程复制到指定的数组中 |
static Map |
getAllStackTraces() Returns a map of stack traces for all live threads. 返回所有活动线程的堆栈跟踪的一个映射 |
ClassLoader |
getContextClassLoader() Returns the context ClassLoader for this Thread. 返回该线程的上下文ClassLoader |
Thread.UncaughtExceptionHandler |
getUncaughtExceptionHandler() Returns the handler invoked when this thread abruptly terminates due to an uncaught exception. 返回该线程由于未捕获异常而突然终止时调用的处理器 |
long |
getId() Returns the identifier of this Thread. 返回该线程的标识符 |
String |
getName() Returns this thread's name. 返回线程的名称 |
int |
getPriority() Returns this thread's priority. 返回该线程的优先级 |
返回所有 |
Thread.State |
getState() Returns the state of this thread. 返回该线程的状态 |
ThreadGroup |
getThreadGroup() Returns the thread group to which this thread belongs. 返回该线程属于的那个线程组 |
static void |
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread. 设置线程由于未捕获异常而突然终止时调用的默认处理器 |
void |
setName(String name) Changes the name of this thread to be equal to the argument 设置线程名 |
void |
setPriority(int newPriority) Changes the priority of this thread. 设置线程优先级 |
void |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) Set the handler invoked when this thread abruptly terminates due to an uncaught exception. 设置该线程由于未捕获异常而突然终止时调用的处理器 |
static void |
sleep(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 void |
sleep(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. 与上类似 |
void |
run() If this thread was constructed using a separate 如果该线程是使用独立的Runnable运行对象构建的,则调用该Runnable对象的run()方法;否则,该方法不执行任何操作并返回 |
void |
setContextClassLoader(ClassLoader cl) Sets the context ClassLoader for this Thread. 设置该线程的上下文ClassLoader |
void |
setDaemon(boolean on) Marks this thread as either a daemon thread or a user thread. 标记该线程是守护线程还是用户线程 |
void |
start() Causes this thread to begin execution; the Java Virtual Machine calls the 启动线程 |
void |
停止线程,不推荐使用,线程不安全 |
static void |
yield() A hint to the scheduler that the current thread is willing to yield its current use of a processor. 暂停执行当前正在运行的线程,并执行其他线程,不推荐使用 |
void |
interrupt() Interrupts this thread. 中断该线程 |
static boolean |
interrupted() Tests whether the current thread has been interrupted. 测试当前线程是否已经中断,如果中断就清除它的中断状态 |
boolean |
isInterrupted() Tests whether this thread has been interrupted. 测试该线程是否中断,不影响线程状态 |
void |
join() Waits for this thread to die. 等待该线程终止 |
void |
join(long millis) Waits at most 最多等待该线程在 |
void |
join(long millis, int nanos) Waits at most 最多等待该线程在 |
boolean |
isAlive() Tests if this thread is alive. 检查该线程活动转台 |
static boolean |
holdsLock(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
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
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()方法和机制
void |
interrupt() Interrupts this thread. 中断线程,但没有返回结果,是唯一能将中断状态设置为true的方法 |
static boolean |
interrupted() Tests whether the current thread has been interrupted. 测试当前线程是否已经中断,如果中断,就清除它的中断状态 |
boolean |
isInterrupted() 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");
}
}
运行结果
线程常用方法再讲
守护线程
void |
setDaemon(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());
}
}
运行结果
线程组