提供两种方法 一种利用Thread join,另一种使用线程同步锁 实测可行 有详细注释 望采纳
public class Test {
private String key;
private Thread myThread = new Thread() {
public void run() {
String threadKey = key.replace(" ", "").replace("-", "");
System.out.println(threadKey);
}
};
public void doTask() {
key = "aa";
myThread.start();
// Thread join 可使得多线程间并行执行变为串行执行
// myThread join 到主线程 必须等 myThread 执行完 主线程才能继续
try {
myThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
key = null;
}
public static void main(String[] args) {
Test test = new Test();
test.doTask();
}
}
public class Test {
private String key;
private Thread myThread = new Thread() {
public void run() {
String threadKey = key.replace(" ", "").replace("-", "");
System.out.println(threadKey);
// myThread 执行完毕 释放主线程锁
synchronized (Test.this) {
Test.this.notifyAll();
}
}
};
public void doTask() {
key = "aa";
myThread.start();
// 把主线程锁起来
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
key = null;
}
public static void main(String[] args) {
Test test = new Test();
test.doTask();
}
}