java多线程2:Thread中的方法
静态方法:
Thread类中的静态方法表示操作的线程是"正在执行静态方法所在的代码块的线程"。
为什么Thread类中要有静态方法,这样就能对CPU当前正在运行的线程进行操作。下面来看一下Thread类中的静态方法:
1:currentThread
/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
public static native Thread currentThread();
currentThread()方法返回的是对当前正在执行线程对象的引用。
/**
* 测试Thread.currentThread():返回代码段正在被哪个线程调用的信息
* this 始终表示线程实例本身
*
* @author yuxiaoyu
*/
public class Mythread4 extends Thread {
static {
System.out.println("Mythread4静态块的打印:Thread.currentThread().getName()=" + Thread.currentThread().getName());
}
public Mythread4() {
System.out.println("Mythread4构造方法:Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Mythread4构造方法:this.getName()=" + this.getName());
} public void run() {
System.out.println("run 方法:Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("run 方法:this.getName()=" + this.getName());
} }
@Test
public void test4() {
Mythread4 a = new Mythread4();
a.start();
}
执行结果:
Mythread4静态块的打印:Thread.currentThread().getName()=main
Mythread4构造方法:Thread.currentThread().getName()=main
Mythread4构造方法:this.getName()=Thread-0
run 方法:Thread.currentThread().getName()=Thread-0
run 方法:this.getName()=Thread-0
这个结果说明,线程类的构造方法、静态块是被main线程调用的,而线程类的run()方法才是应用线程自己调用的,this 始终表示线程实例本身。
2:sleep
/**
* 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. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static native void sleep(long millis) throws InterruptedException;
该方法是让正在执行的线路休眠指定毫秒,注意API的注释中“The thread does not lose ownership of any monitors.”表示线程不会失去任何监视器的所有权。
简单说就是sleep代码上下文如果被加锁了,那么在休眠的时间内,锁依然在,但是CPU资源会让出给其他线程。
3:yield
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
public static native void yield();
该方法表示给调度程序的一个提示:当前线程愿意让出它当前对处理器的使用。调度程序可以自由地忽略这个提示。
public class Mythread5 extends Thread {
public void run() {
long beginTime = System.currentTimeMillis();
int count = 0;
for (int i = 0; i < 50000000; i++)
{
Thread.yield();
count = count + i + 1;
}
long endTime = System.currentTimeMillis();
System.out.println("用时:" + (endTime - beginTime) + "毫秒!");
}
}
第一次运行结果:用时:34872毫秒!
第二次运行结果:用时:33738毫秒!
如果将 Thread.yield(); 注释掉的话, 运行结果:用时:48毫秒!。
看到,每次执行的用时都不一样,证明了yield()方法放弃CPU的时间并不确定,而且yield方法将CPU资源让给其他资源导致变慢。
4:interrupted()
/**
* Tests whether the current thread has been interrupted. The
* <i>interrupted status</i> of the thread is cleared by this method. In
* other words, if this method were to be called twice in succession, the
* second call would return false (unless the current thread were
* interrupted again, after the first call had cleared its interrupted
* status and before the second call had examined it).
*
* <p>A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
*
* @return <code>true</code> if the current thread has been interrupted;
* <code>false</code> otherwise.
* @see #isInterrupted()
* @revised 6.0
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);
测试当前线程是否已经中断,并清除线程的中断状态。
实例方法
1:start
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this); boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
此方法告诉线程执行器,这个线程可以执行了。
2:isAlive
/**
* Tests if this thread is alive. A thread is alive if it has
* been started and has not yet died.
*
* @return <code>true</code> if this thread is alive;
* <code>false</code> otherwise.
*/
public final native boolean isAlive();
判断当前的线程是否处于活动状态,活动状态就是线程已经启动且尚未终止。线程处于正在运行或准备开始运行的状态,就认为线程是“存活”的。
public class Mythread7_2 extends Thread {
public Mythread7_2() {
System.out.println("Mythread7_2---begin");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive());
System.out.println("this.getName()=" + this.getName());
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("Mythread7_2---end");
}
@Override
public void run() {
System.out.println("run---begin");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()=" + Thread.currentThread().isAlive());
System.out.println("this.getName()=" + this.getName());
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("run---end");
}
}
@Test
public void test7_2() {
Mythread7_2 c = new Mythread7_2();
System.out.println("main begin t1 isAlive=" + c.isAlive());
c.setName("A");
c.start();
System.out.println("main end t1 isAlive=" + c.isAlive());
}
执行结果:
Mythread7_2---begin
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()=true
this.getName()=Thread-0
this.isAlive()=false
Mythread7_2---end
main begin t1 isAlive=false
run---begin
Thread.currentThread().getName()=A
Thread.currentThread().isAlive()=true
this.getName()=A
this.isAlive()=true
run---end
main end t1 isAlive=false
可以看出:只有在当前实例对象调用了start方法时,this.isAlive()才返回true。
3:interrupt
/**
* Interrupts this thread.
*
* <p> Unless the current thread is interrupting itself, which is
* always permitted, the {@link #checkAccess() checkAccess} method
* of this thread is invoked, which may cause a {@link
* SecurityException} to be thrown.
*
* <p> If this thread is blocked in an invocation of the {@link
* Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
* Object#wait(long, int) wait(long, int)} methods of the {@link Object}
* class, or of the {@link #join()}, {@link #join(long)}, {@link
* #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
* methods of this class, then its interrupt status will be cleared and it
* will receive an {@link InterruptedException}.
*
* <p> If this thread is blocked in an I/O operation upon an {@link
* java.nio.channels.InterruptibleChannel InterruptibleChannel}
* then the channel will be closed, the thread's interrupt
* status will be set, and the thread will receive a {@link
* java.nio.channels.ClosedByInterruptException}.
*
* <p> If this thread is blocked in a {@link java.nio.channels.Selector}
* then the thread's interrupt status will be set and it will return
* immediately from the selection operation, possibly with a non-zero
* value, just as if the selector's {@link
* java.nio.channels.Selector#wakeup wakeup} method were invoked.
*
* <p> If none of the previous conditions hold then this thread's interrupt
* status will be set. </p>
*
* <p> Interrupting a thread that is not alive need not have any effect.
*
* @throws SecurityException
* if the current thread cannot modify this thread
*
* @revised 6.0
* @spec JSR-51
*/
public void interrupt() {
if (this != Thread.currentThread())
checkAccess(); synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
interrupt并不会立刻停止线程,interrupt0的作用仅仅是为当前线程打一个中断的标志。
4:isInterrupted
/**
* Tests whether this thread has been interrupted. The <i>interrupted
* status</i> of the thread is unaffected by this method.
*
* <p>A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
*
* @return <code>true</code> if this thread has been interrupted;
* <code>false</code> otherwise.
* @see #interrupted()
* @revised 6.0
*/
public boolean isInterrupted() {
return isInterrupted(false);
}
测试线程是否已经中断,但不清除状态标识。这个和interrupted()方法区别就是不清除状态标识。
参考文献
1:《Java并发编程的艺术》
2:《Java多线程编程核心技术》
java多线程2:Thread中的方法的更多相关文章
- java 多线程 2 Thread中start()和run()的区别
- JAVA多线程实现的三种方法
JAVA多线程实现方式主要有三种:继承Thread类.实现Runnable接口.使用ExecutorService.Callable.Future实现有返回结果的多线程.其中前两种方式线程执行完后都没 ...
- (二)线程Thread中的方法详解
1.start() start()方法的作用讲得直白点就是通知"线程规划器",此线程可以运行了,正在等待CPU调用线程对象得run()方法,产生一个异步执行的效果.通过start( ...
- 线程Thread中的方法详解(二)
1.start() start()方法的作用讲得直白点就是通知"线程规划器",此线程可以运行了,正在等待CPU调用线程对象得run()方法,产生一个异步执行的效果.通过start( ...
- java:多线程(代理模式,Thread中的方法,Timer,生产者和消费者)
*进程:一个正在运行的程序,进程是操作系统分配资源的基本单位,每个进行有独立的内存空间,进程之间切换开销较大. *线程:一个轻量级的进程,线程是任务调度的基本单位,一个进程可以有多个线程, * 系统没 ...
- java多线程创建-Thread,Runnable,callable和threadpool
java创建多线程的方式有许多种,这里简要做个梳理 1. 继承Thread类 继承java.lang.Thread类,创建本地多线程的类,重载run()方法,调用Thread的方法启动线程.示例代码如 ...
- Java多线程01(Thread类、线程创建、线程池)
Java多线程(Thread类.线程创建.线程池) 第一章 多线程 1.1 多线程介绍 1.1.1 基本概念 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于 ...
- java多线程有几种实现方法?线程之间如何同步
java中多线程的实现方法有两种:1.直接继承thread类:2.实现runnable接口: 同步的实现方法有五种:1.同步方法:2.同步代码块:3.使用特殊域变量(volatile)实现线程同步:4 ...
- JAVA多线程(一) Thread & Runnable
githut代码地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service/ ...
随机推荐
- silky微服务的应用服务和服务条目
目录 服务的定义 服务条目 根据服务条目生成WebAPI 服务条目的治理特性 缓存拦截 服务条目的例子 服务的实现 开源地址 在线文档 服务的定义 服务接口是微服务定义服务的基本单位,定义的应用服务接 ...
- 菜鸡的Java笔记 - java 断言
断言:assert (了解) 所谓的断言指的是在程序编写的过程之中,确定代码执行到某行之后数据一定是某个期待的内容 范例:观察断言 public class Abnorma ...
- 菜鸡的Java笔记 第二十一 final 关键字
使用final定义类,属性,方法 final在一些书中被称为终结器,意思是:利用final定义的类不能够有子类,利用final定义的方法不能够被覆写,利用final定义的变量就成 ...
- vue + cesium开发(5) 搭建 vue + cesium开发环境(2)
上vue+cesium开发(1)中,没有进行配置webpack,而是使用了插件进行代替,在使用过程中出现了一些未知BUG,影响体验,因此参考了官方文档对项目进行重新配置,使用了 copy-webpac ...
- vue2与vue3的差异(总结)?
vue作者尤雨溪在开发 vue3.0 的时候开发的一个基于浏览器原生 ES imports 的开发服务器(开发构建工具).那么我们先来了解一下vite Vite Vite,一个基于浏览器原生 ES i ...
- MYSQL数据库重新初始化
前言 我们在日常开发过程中,可能会遇到各种mysql服务无法启动的情况,各种百度谷歌之后,依然不能解决的时候,可以考虑重新初始化mysql.简单说就是重置,"恢复出厂设置".重置之 ...
- [atAGC054C]Roughly Sorted
考虑对于确定的排列$\{p_{i}\}$,如何求出其(交换后)会得到的排列-- 令$cnt_{x}$为在$i$之前比$x$大的元素个数(其中$p_{i}=x$),显然排列合法当且仅当$cnt_{i}\ ...
- [loj2461]完美的队列
参考论文,这里一共写了论文中的3种做法,第一种做法为强制在线时的做法,第二种为时间复杂度略高的做法(前两种都无法通过),第三种为本题正解,并给出了一种理论复杂度更优的做法 1.做法1 情况1 $\fo ...
- rm命令弱爆了!
大家好,我是良许. 创建.删除和修改文件是用户在 Linux 系统中执行的非常常见操作.大家都知道,在 Linux 系统里使用 rm 命令删除单个文件时,几乎一瞬间就完成了.但是如果文件数量很大,那么 ...
- Codeforces 1097G - Vladislav and a Great Legend(第二类斯特林数+树上背包)
Codeforces 题目传送门 & 洛谷题目传送门 首先看到这题我的第一反应是:这题跟这题长得好像,不管三七二十一先把 \(k\) 次方展开成斯特林数的形式,\(f(X)^k=\sum\li ...