Java多线程技术
2015-07-31 11:50
543 查看
在Java中,虚拟CPU是自动封装进Thread类的实例中,而Code和Data要通过一个对象传给Thread类的构造函数。
public interface Runnable
Tip:设计该类的目的就是为希望在活动时执行代码的对象提供一个公共协议。
public class Thread extends Object
implements Runnable
Tip:运行一个程序,即开启了一个进程和至少一个线程,干活的是线程而非进程!Java语言内置多线程功能支持,
简化了Java的多线程编程。JVM允许应用程序并发地运行多个执行线程。
public synchronized void start()
<span style="font-size:18px;">/** * 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.</span></span>Tip: 其具体实现方法中,若程序未出现异常,则调用
<span style="font-size:18px;"> private native void start0(); </span>方法,开辟一块新的工作内存供当前线程使用。然后调用该Thread对象的run()方法。
public void run()
<span style="font-size:18px;">/** * If this thread was constructed using a separate * <code>Runnable</code> run object, then that * <code>Runnable</code> object's <code>run</code> method is called; * otherwise, this method does nothing and returns. * <p> * Subclasses of <code>Thread</code> should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } }</span></span></span>
Tip: 如果该线程是使用独立的
Runnable
运行对象构造的,即
target != null
则调用该
Runnable对象的
run方法;否则,该方法不执行任何操作并返回。
public static native void sleep(long millis) throws InterruptedException
/** * 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.
* @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. */
Tip:sleep方法是Thread类的方法,表示让Thread.currentThread()在指定的毫秒数内暂停执行。因为是静态的方法,所以一个CPU
在运行时只能令一个线程休眠。只有当该休眠线程睡了足够时间或被interrupt,其他线程才能够进入休眠状态。此外,sleep 方法的本地实现中,不需要释放锁。比较于wait和notify方法的本地实现中需要先释放锁,所以sleep方法可以在任何地方使
用,而wait、notify方法只能在synchronized同步方法或同步代码块中使用。
public void interrupt()
/** * Interrupts this thread. * * <p> Unless the current thread is interrupting itself, which is * always permitted, the {@link #checkAccess() checkAccess} method * o c2e1 f 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(); <span style="color:#ff0000;"><strong>// Just to set the interrupt flag</strong></span> b.interrupt(this); return; } } interrupt0(); }
API中文:中断线程。
如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的
checkAccess方法就会被调 用,这可能抛出
SecurityException。
如果线程在调用
Object类的
wait()、
wait(long)或
wait(long, int)方法,或者该类的
join()、
join(long)、
join(long, int)、
sleep(long)
或
sleep(long, int)方法过程中受阻,则其中断 状态将被清除,它还将收到一个
InterruptedException。
如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该 线程将收到一个
ClosedByInterruptException。
如果该线程在一个
Selector中受阻,则该线程的中断状态将被设置,它将立即从选择操作返回,并可能 带有一个非零值,就好像调用了选择器的
wakeup方法一样。
如果以前的条件都没有保存,则该线程的中断状态将被设置。
中断一个不处于活动状态的线程不需要任何作用。
Tip: interrupt()只是改变中断状态而已. interrupt()不会中断一个正在运行的线程。这一方法实际上完成的是,给受阻塞的线程抛出一
个中断信号。更确切 的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,那么,当调用interrupt()
时,它将接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态。
如果线程没有被阻塞,这时调用interrupt()将不起作用;否则,线程就将得到InterruptedException异常(该线程必须事先预备好
处理此状况),接着逃离阻塞状态。
public static void yield()
/** * A hint to the scheduler that the current thread is <span style="color:#3366ff;">willing <img alt="哭" src="http://static.blog.csdn.net/xheditor/xheditor_emot/default/cry.gif" /></span> 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();
Tip: yield(屈服,投降;退位,让位),暂停当前正在执行的线程对象,并执行其他线程。或许是早先英语不好,不知怎么就理 解为打嗝了。——当前正在执行的线程对象因抢到了CPU执行权而欢天喜地的执行着自己的代码的时候,突然JVM让其打了个隔
~~~,然后就得苦逼的再来和其他线程兄弟们重新抢夺CPU执行权,还能不能抢的过就另说了。。
public final void join() throwsInterruptedException
<span style="color:#3333ff;">/** * </span><span style="color:#ff0000;"><strong>Waits</strong></span><span style="color:#3333ff;"><strong> </strong>for this thread to die. * * <p> An invocation of this method behaves in exactly the same * way as the invocation * * <blockquote> * {@linkplain #join(long) join}{@code (0)} * </blockquote> * * @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 final void join() throws InterruptedException { <span style="background-color: rgb(255, 204, 51);">join(0);</span> }</span>
Tip: (Waitsfor
this thread to die.)等待该线程终止。
who wait? MainThread
how to waits? public finalsynchronizedvoidjoin(long millis) throws InterruptedExceptio
当 a thread 调用join方法的时候,MainThread 就被停止执行,直到 a thread 线程执行完毕。
相关文章推荐
- jdk1.8 日期新API LocalDateTime,LocalDate,LocalTime 在Hibernate中无法反序列化解决方法
- spring零总
- hadoop start-dfs.sh Error: JAVA_HOME is not set and could not be found
- java.lang.NoClassDefFoundError: org/openqa/selenium/htmlunit/HtmlUnitDriver 问题解决方案
- Java实现责任链模式
- Java压缩技术(四) GZIP——Java原生实现
- 10种常见的Java不规范代码
- springMVC 前后台日期格式传值解决方式之二(共二) @InitBinder的使用
- 使用 NIO.2 遍历目录下所有的Java文件
- struts2登陆拦截器 (FIX)
- 关于eclipse中egit右键reset失败,无法更新git仓库.
- (LeetCode)杨辉三角形Pascal's Triangle
- Eclipse 快捷键大全
- Spring MVC的@ResponseBody返回JSON串
- spring controller里模拟post提交,返回结果异常
- springMVC 前后台日期格式传值解决方式之一(共二) @DateTimeFormat的使用和配置
- 使用Spring AOP切面解决数据库读写分离
- java注解
- Lowest Common Ancestor of a Binary Search Tree Java LeetCode
- Java使用MyEclipse构建webService简单案例