您的位置:首页 > 其它

一个多线程例子

2013-01-15 17:17 211 查看
class Info {
public synchronized void hold() throws InterruptedException {
this.wait();
}
public synchronized void run() {
this.notifyAll();
}
}

public class TestThread extends Thread {
public int i = 0;
public Info info;
public int stop = 0;
public int start = 0;

public int getStop() {
return stop;
}

public void setStop(int stop) {
this.stop = stop;
}

public int getStart() {
return start;
}

public void setStart(int start) {
this.start = start;
}

public TestThread(Info info, int stop, int start) {
this.stop = stop;
this.start = start;
this.info = info;
}

@Override
public void run() {
while (i < 20) {
if (i == stop) {
try {
info.hold();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i==start){
info.run();
}
i++;
System.out.println(Thread.currentThread().getName()+":"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Info info = new Info();
TestThread t1 = new TestThread(info, 8, -1);
TestThread t2 = new TestThread(info,5,-1);
TestThread t3 = new TestThread(info,-1,10);

t1.setName("a");
t2.setName("b");
t3.setName("main");
t3.start();
t1.start();
t1.setStop(5);
t2.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: