public class ThreadWait extends Thread{
Queue q;
public ThreadWait(Queue q,String name) {
// Thread th1=new Queue(this,"生产");
// Thread th2=new Queue(this,"消费");
// th1.start();
// th2.start();
super(name);
this.q=q;
// TODO Auto-generated constructor stub
} int i=1;
public synchronized void run(){
if(Thread.currentThread().getName().equals("生产")){
while(true){
synchronized(this){
if(i<=10){
q.put(i);
System.out.println(Thread.currentThread().getName()+"put "+i++);
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
if(Thread.currentThread().getName().equals("消费")){
while(true){
synchronized(this){
// while(true){
q.get();
System.out.println(getName()+"get:"+q.get());
notifyAll();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
}
}
}
}
public static void main(String []args){
Queue q=new Queue();
Thread th1= new ThreadWait(q,"生产");
ThreadWait th2=new ThreadWait(q,"消费"); th1.start();
th2.start();
}
} class Queue {
int i; public void put(int i){
this.i=i;
}
public int get(){
return i;
}
//public void run() {
// // TODO Auto-generated method stub
//
//}
}
Queue q;
public ThreadWait(Queue q,String name) {
// Thread th1=new Queue(this,"生产");
// Thread th2=new Queue(this,"消费");
// th1.start();
// th2.start();
super(name);
this.q=q;
// TODO Auto-generated constructor stub
} int i=1;
public synchronized void run(){
if(Thread.currentThread().getName().equals("生产")){
while(true){
synchronized(this){
if(i<=10){
q.put(i);
System.out.println(Thread.currentThread().getName()+"put "+i++);
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
if(Thread.currentThread().getName().equals("消费")){
while(true){
synchronized(this){
// while(true){
q.get();
System.out.println(getName()+"get:"+q.get());
notifyAll();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
}
}
}
}
public static void main(String []args){
Queue q=new Queue();
Thread th1= new ThreadWait(q,"生产");
ThreadWait th2=new ThreadWait(q,"消费"); th1.start();
th2.start();
}
} class Queue {
int i; public void put(int i){
this.i=i;
}
public int get(){
return i;
}
//public void run() {
// // TODO Auto-generated method stub
//
//}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货