62,623
社区成员
发帖
与我相关
我的任务
分享
public class SumThread extends Thread {
int total = 0;
private Object object;
public SumThread(Object object) {
super();
this.object = object;
}
public void run() {
synchronized (this) {
for (int i = 1; i <= 100; i++) {
total += i;
try {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 通知;
//this.notify();
}
}
}
public class ThreadInteractionTest {
public static void main(String[] args) {
Object object = new Object();
SumThread st = new SumThread(object);
// 启动计算线程
st.start();
// 这里传入object和使用st似乎存在差别;
synchronized (st) {
// 注意比较有notify()和无notify()间的差别
try {
System.out.println("等待对象sum完成计算。。。");
// 等待;
st.wait();
// 超时等待;
//st.wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sum对象计算的总和是:" + st.total);
}
}
}
public class SumThread extends Thread {
int total = 0;
private Object object;
public SumThread(Object object) {
super();
this.object = object;
}
public void run() {
synchronized (object) {
for (int i = 1; i <= 100; i++) {
total += i;
try {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 通知;
object.notify();
}
}
}
public class ThreadInteractionTest {
public static void main(String[] args) {
Object object = new Object();
SumThread st = new SumThread(object);
// 启动计算线程
st.start();
// 这里传入object和使用st似乎存在差别;
synchronized (object) {
// 注意比较有notify()和无notify()间的差别
try {
System.out.println("等待对象sum完成计算。。。");
// 等待;
object.wait();
// 超时等待;
//st.wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sum对象计算的总和是:" + st.total);
}
}
}
System.out.println("线程沉睡");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* This method is called by the system to give a Thread
* a chance to clean up before it actually exits.
*/
private void exit() {
if (group != null) {
group.threadTerminated(this);
group = null;
}
/* Aggressively null out all reference fields: see bug 4006245 */
target = null;
/* Speed the release of some of these resources */
threadLocals = null;
inheritableThreadLocals = null;
inheritedAccessControlContext = null;
blocker = null;
uncaughtExceptionHandler = null;
}
以上的代码,说明在线程终止时,系统会调用exit()方法。
而在exit()方法中,也就是代码的第7行,会调用group.threadTerminated(this);
这个方法的源代码如下:
/**
* Notifies the group that the thread {@code t} has terminated.
*
* <p> Destroy the group if all of the following conditions are
* true: this is a daemon thread group; there are no more alive
* or unstarted threads in the group; there are no subgroups in
* this thread group.
*
* @param t
* the Thread that has terminated
*/
void threadTerminated(Thread t) {
synchronized (this) {
remove(t);
if (nthreads == 0) {
notifyAll();
}
if (daemon && (nthreads == 0) &&
(nUnstartedThreads == 0) && (ngroups == 0))
{
destroy();
}
}
}
在上面这段代码中的第17行,会看notifyAll();的调用。
同时,可以参看join()方法的源代码中,你也会看到wait()方法的执行,那么什么时候当前线程会被唤醒呢,应该也是在线程终结时。
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait 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 final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public final void wait() throws InterruptedException {
wait(0);
}
这是Object类中源码,调用的是:
public final native void wait(long timeout) throws InterruptedException;
这段代码注释中,确实有如你所提示的这一段:
This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:
•Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
•Some other thread invokes the notifyAll method for this object.
•Some other thread interrupts thread T.
•The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
重要的是第3条,也就是粗体标识的这一条。问题是这里的字面含义翻译过来是:
其它线程中断了线程T(当前线程,也就是上面的主线程)。
这里,主线程似乎没有被中断啊?
而最后一句也在说,如果超时时间为0,线程只做等待,直到被通知。

