62,614
社区成员
发帖
与我相关
我的任务
分享
public class WaitTest {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
// synchronized (this) {
System.out.println("ThreadB");
for (int i = 0; i < 50; i++) {
total += i;
try {
Thread.sleep(100);
System.out.print(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// notify();
System.out.println();
}
// }
}
/**
* Removes the specified Thread from this group.
* @param t the Thread to be removed
* @return if the Thread has already been destroyed.
*/
void remove(Thread t) {
synchronized (this) {
if (destroyed) {
return;
}
for (int i = 0 ; i < nthreads ; i++) {
if (threads[i] == t) {
System.arraycopy(threads, i + 1, threads, i, --nthreads - i);
// Zap dangling reference to the dead thread so that
// the garbage collector will collect it.
threads[nthreads] = null;
break;
}
}
if (nthreads == 0) {
notifyAll();
}
if (daemon && (nthreads == 0) &&
(nUnstartedThreads == 0) && (ngroups == 0))
{
destroy();
}
}
}
但奇怪的是线程退出,其group也被设置为了null,貌似认为当前thread就是当前thread group中的唯一一个thread了package com.love.yan.xing;
class ThreadB extends Thread {
int total;
public void run() {
// synchronized (this) {
System.out.println("ThreadB");
for (int i = 0; i < 50; i++) {
total += i;
try {
Thread.sleep(100);
System.out.print(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized(new WaitTest().yan()){
new WaitTest().yan().notify();
}
System.out.println();
}
// }
}
package com.love.yan.xing;
public class WaitTest {
static ThreadB b = new ThreadB();
public static void main(String[] args) {
ThreadB a = new ThreadB();
a.start();
synchronized (b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
public Thread yan(){
return b;
}
}
用以上代码测试了一下,唤醒时,也必须对等待的对象同步。以下猜测:你的代码ThreadB线程,又作为同步对象,首先打印Waiting for b to complete...然后等待,执行的线程和同步的对象是同一个对象,会不会是run方法执行完,不需要去唤醒同步的对象,仅是猜测。。。public class WaitTest {
public static Object o = new Object();
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (o) {
try {
System.out.println("Waiting for b to complete...");
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized (WaitTest.o) {
System.out.println("ThreadB");
for (int i = 0; i < 50; i++) {
total += i;
try {
Thread.sleep(100);
System.out.print(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
WaitTest.o.notify();
System.out.println();
}
}
}
我的版本,新建一个object用于同步,你的thread又是线程又作为同步用途,看起来别扭