public class printer{
public static ArrayList
public String msg;
static class task extends Thread{
public boolean running=false;
public task(){
this.running=true;
super.start();
}
public void stopit(){
running=false;
}
public void run(){
int i=0;
synchronized(this){
try{
while(running){
if(msgs.size()>10){
System.out.println("task is waiting...");
wait();
//System.out.println("errrrrrrrrrrrrrrrr");
}
msgs.add("task "+i);
System.out.println("添加 task"+i);
notify();
System.out.println("task唤醒等待进程");
Thread.sleep(1000);
i++;
}
}catch(InterruptedException ie){}
}
}
}
static class printit extends Thread {
public boolean running=false;
public printit(){
running=true;
super.start();
}
public void stopit(){
running=false;
}
public void run(){
synchronized(this){
try{
while(running){
if(msgs.size()<=0){
System.out.println("printit is waiting task");
wait();
}
System.out.println("打印 "+msgs.remove(0));
notify();
System.out.println("printit唤醒等待线程");
Thread.sleep(700);
}
}catch(InterruptedException ie){}
}
}
}
public static void main(String args[]){
msgs=new ArrayList
new task();
new printit();
}
}
miucat 于 2009-07-04 12:41:16发表:
添加 task0
task唤醒等待进程
打印 task 0
printit唤醒等待线程
printit is waiting task
添加 task1
task唤醒等待进程
添加 task2
task唤醒等待进程
添加 task3
task唤醒等待进程
添加 task4
task唤醒等待进程
添加 task5
task唤醒等待进程
添加 task6
task唤醒等待进程
添加 task7
task唤醒等待进程
添加 task8
task唤醒等待进程
添加 task9
task唤醒等待进程
添加 task10
task唤醒等待进程
添加 task11
task唤醒等待进程
task is waiting...
p.s.以上是运行结果。
这个还是理解不了。