线程的问题,为什么运行完后线程没有自动关闭
package thread;
public class ThreadPrint {
public static void main(String[] args) {
String lock="lock";
Thread t1= new Thread(new Thread1(lock));
t1.start();
Thread t2= new Thread(new Thread2(lock));
t2.start();
}
}
class Thread1 implements Runnable{
String lock;
public Thread1(String lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
for(int i = 1;i<53;i++){
System.out.println("The first thread.-->"+i);
if(i%2==0){
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Thread2 implements Runnable{
String lock;
public Thread2(String lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
for(char i = 'A';i<'Z';i++){
try {
System.out.println("The second thread.-->"+i);
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
[解决办法]
你可以亲手杀死进程,比如
public class ThreadPrint { public static void main(String[] args) throws Exception { String lock = "lock"; Thread t1 = new Thread(new Thread1(lock)); t1.start(); Thread.sleep(1000); t1.stop(); Thread t2 = new Thread(new Thread2(lock)); t2.start(); Thread.sleep(1000); t2.stop(); }}class Thread1 implements Runnable { String lock; public Thread1(String lock) { this.lock = lock; } public void run() { synchronized (lock) { for (int i = 1; i < 53; i++) { System.out.println("The first thread.-->" + i); if (i % 2 == 0) { try { lock.notify(); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }}class Thread2 implements Runnable { String lock; public Thread2(String lock) { this.lock = lock; } public void run() { synchronized (lock) { for (char i = 'A'; i < 'Z'; i++) { try { System.out.println("The second thread.-->" + i); lock.notify(); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } }}
[解决办法]
Thread-0:0
Thread-1:A
Thread-0:1
Thread-0:2
Thread-1:B
Thread-0:3
Thread-0:4
Thread-1:C
Thread-0:5
Thread-0:6
Thread-1:D
Thread-0:7
Thread-0:8
Thread-1:E
Thread-0:9
Thread-0:10
Thread-1:F
Thread-0:11
Thread-0:12
Thread-1:G
Thread-0:13
Thread-0:14
Thread-1:H
Thread-0:15
Thread-0:16
Thread-1:I
Thread-0:17
Thread-0:18
Thread-1:J
Thread-0:19
Thread-0:20
Thread-1:K
Thread-0:21
Thread-0:22
Thread-1:L
Thread-0:23
Thread-0:24
Thread-1:M
Thread-0:25
Thread-0:26
Thread-1:N
Thread-0:27
Thread-0:28
Thread-1:O
Thread-0:29
从运行的结果可以知道,在Thread1 运行到30的时候,不会进入到循环了。但是,你并没有释放lock锁,而Thread2还在等待lock锁,这样就导致了,线程一直等待了。注:当调用wait()方法后,只有调用了notify()方法后才会释放锁的