关于线程同步锁的问题
为什么这个类里面 用 Integer 这个对象作为锁 就没问题
这个是卖票问题
public class TestTicket {
public static void main(String[]args){
SubThread su= new SubThread();
Thread t1= new Thread(su);
Thread t2= new Thread(su);
Thread t3 =new Thread(su);
t1.start();
t2.start();
t3.start();
}
}
class SubThread implements Runnable{
private Integer i=12;
private int ticket=1000;
public void run(){
while(true){
synchronized(i){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"---"+ticket--);
}
}
}
}
}
而到了这个
这是个消费者和生产者的问题
用 Integer 用会报错呢
我用this
就不会报错
public class TestMyCommunication {
public static void main(String[]args){
Student stu= new Student();
school s= new school(stu);
company c=new company(stu);
Thread t=new Thread(s);
Thread t2=new Thread(c);
t.start();
t2.start();
}
}
class school implements Runnable{
private Student stu;
public school(Student stu){
this.stu=stu;
}
public void run(){
while(true){
stu.put();
}
}
}
class company implements Runnable{
private Student stu;
public company(Student stu){
this.stu=stu;
}
public void run(){
while(true){
stu.pop();
}
}
}
class Student{
private String name;
private String 易做图;
boolean isFull=false;
int index=0;
private Integer test=10;
public void put(){
synchronized(test){
if(!isFull){
if(index%2==0){
name="黄盖";
易做图="男";
}else{
name="小乔";
易做图="女";
}
index++;
isFull=true;
notify();
}
}
}
public void pop(){
synchronized(test){
if(isFull){
System.out.println(name+"/"+易做图);
isFull=false;
notify();
}
}
}
}
--------------------编程问答-------------------- 你用new Integer(12) --------------------编程问答--------------------
跟这没关系吧 他会自动封箱的
补充:Java , Java SE