62,620
社区成员
发帖
与我相关
我的任务
分享
public class InterruputTest {
public static volatile int flag = 10;
public static Object synObj = new Object();
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
Thread.sleep(1000);
t1.interrupt();
}
static class Thread1 extends Thread {
public void run(){
synchronized (synObj) {
while(flag>=10){
try {
synObj.wait();
} catch (InterruptedException e) {
flag = 1;
System.out.println("Thread1 has been interrupted!");
}
}
}
}
}
static class Thread2 extends Thread {
public void run(){
synchronized (synObj) {
while(true){
if(flag<10){
System.out.println("flag=" + flag);
}
flag=10;
}
}
}
}
}
public class Interrupt {
Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
new Interrupt().foo();
}
Thread thread1;
Thread thread2;
private void foo() throws InterruptedException {
thread1 = new Thread1();
thread2 = new Thread2();
thread1.start();
thread2.start();
new Thread() {
{
setDaemon(true);
}
@Override
public void run() {
boolean b1 = false;
boolean b2 = false;
while (true) {
if (b1 != (b1 = thread1.isInterrupted()))
System.out.println("thread1.isInterrupted()" + thread1.isInterrupted());
if (b2 != (b2 = thread2.isInterrupted()))
System.out.println("thread2.isInterrupted()" + thread2.isInterrupted());
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
}.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
thread2.interrupt();
// thread2.stop();
}
class Thread1 extends Thread {
@Override
public void run() {
boolean once = true;
synchronized (lock) {
for (int i = 0; i < 10; i++) {
System.out.println("Thread1 running.");
if (once) {
once = false;
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println("wait interrupted,isInterrupted=false");
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
}
}
}
class Thread2 extends Thread {
@Override
public void run() {
boolean once = true;
synchronized (lock) {
while (true) {
System.out.println("Thread2 running");
try {
Thread.sleep(500);
if (once) {
once = false;
System.out.println("Interrupt Thread1.");
thread1.interrupt();
// lock.notify();
}
} catch (InterruptedException e) {
System.out.println("Thread2 end.");
return;
}
}
}
}
}
}