java中的线程同步问题二
刚才没有给t加上同步锁,现在给t加上synchronized关键字,实现线程对资源的锁定,代码如下:
package com.Test.yhy;
import java.lang.Thread;
public class Ex8_8{
public static void main(String ars[]){
Tickets t = new Tickets(3);
new Producer(t).start();
new Consumer(t).start();
}
}
class Tickets {
int number=0;
int size=0;
boolean available=false;
public Tickets(int size){
this.size = size;
}
}
class Producer extends Thread{
Tickets t=null;
public Producer(Tickets t){
this.t = t;
}
public void run(){
while(t.number<t.size){
synchronized(t){
System.out.println("Producer puts ticket "+(++t.number));
t.available=true;
}
}
}
}
class Consumer extends Thread {
Tickets t=null;
int i=0;
public Consumer(Tickets t){
this.t = t;
}
public void run(){
while(i<t.size){
synchronized(t){
if(t.available==true&&i<=t.number)
System.out.println("Consumer buys tickets "+(++i));
if(i==t.number)
t.available=false;
}
}
}
}
云运行结果省略,反正就是ok,我运行了起码100次,没问题。。我现在又有一个问题了,不能解决,忘大神指教:我现在给生产者代码加上如下代码:class Producer extends Thread{Tickets t=null;public Producer(Tickets t){this.t = t;}public void run(){while(t.number<t.size){synchronized(t){System.out.println("Producer puts ticket "+(++t.number));t.available=true;}try{Thread.sleep(1000);}catch(Exception e){}}}}运行结果如下:就是每一次当消费者消费了票以后,才会sleep1秒钟,而不是在每一张票生产出来后sleep,如果把Thread改成this:try{this.sleep(1000);}catch(Exception e){},怎么会这样呢。。??