1.Thread类中常用方法
Thread类常用方法 | 描述 |
---|---|
start() | 启动当前线程,调用当前线程的run()方法。 |
run() | 通常需要重写该方法,将线程要执行的操作写在此方法中。 |
currentThread() | 静态方法,返回执行当前代码的线程。 |
getName() | 获取当前线程的名字。 |
setName() | 设置当前线程的名字。 |
yield() | 释放当前CPU的执行权。 |
join() | 在线程a中调用线程b的join(),此时线程a就进入了阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。 |
stop() | 此方法已过时,用于强制结束当前线程。 |
sleep(long millitime) | 使当前线程阻塞millitime毫秒。1秒 = 1000毫秒 |
isAlive() | 判断当前线程是否存活。 |
Thread类常用方法
```java
public class Test {
private int priority; //线程优先级,提供getPriority()/set方法
public final static int MIN_PRIORITY = 1; //最低
public final static int NORM_PRIORITY = 5; //默认优先级
public final static int MAX_PRIORITY = 10; //最高
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
@Override
public void run() {
if (target != null) {
target.run();
}
}
public static native Thread currentThread();
public final String getName() {
return name;
}
public final synchronized void setName(String name) {
checkAccess();
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
if (threadStatus != 0) {
setNativeName(name);
}
}
public static native void yield();
public final void join() throws InterruptedException {
join(0);
}
@Deprecated
public final void stop() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
checkAccess();
if (this != Thread.currentThread()) {
security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
}
}
if (threadStatus != 0) {
resume(); // Wake up thread if it was suspended; no-op otherwise
}
stop0(new ThreadDeath());
}
public static native void sleep(long millis) throws InterruptedException;
public final native boolean isAlive();
}
</details>
## 2.用户线程和守护线程
用户线程:运行在前台,main线程。
守护线程:运行在后台,为前台线程提供服务,如垃圾回收。
参考:[Java用户线程和守护线程](https://www.cnblogs.com/myseries/p/12078413.html "Java用户线程和守护线程")