<span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">线程同步,当两个线程同时访问一个对象时,出现同步问题。使用关键字:synchronized</span><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px; background-color: rgb(255, 255, 255);">解决同步有两种:1、 同步方法2、同步代码</span>
</pre><pre name="code" class="java">
<pre name="code" class="html"><span style="font-size:18px;">synchronized(t){
for(int i=0;i<10;i++){
t.a = t.a +i;
System.out.println(this.getName()+"a======"+t.a);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}</span>
线程通信,多个线程同时访问一个对象时,存在同步,这时,就存在线程通信,当一个线程在执行时,另一个线程处在等待的过程中,当这个线程执行完成后,就会通知另一个线程去执行。典型的模型就是“生产消费模型”。简单地说:此模型的规则就是,一个放东西,一个拿东西,只有当放好了的时候才能拿。具体解释是:生产和消费线程共同操作一个集合,生产线程放入对象,消费线程取出对象!仅当集合中没有对象时,生产线程会放入一个对象,如有集合中有一个对象时,消费线程要马上取出这个对象。
public void run() {
super.run();
synchronized (ProductThread.list) {
while (true) {
// 判断仓库是否还有手机
if (ProductThread.list.size() == 0) {
try {
<strong style="background-color: rgb(51, 255, 255);">ProductThread.list.wait();</strong>
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 从队列中移出一个手机
MiPhone mp = ProductThread.list.remove(0);
System.out.println("销售人员卖出了一个手机,手机型号为:" + mp.getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 提醒生产者,手机买完了,你必须继续生产
<span style="color:#ff6666;"><strong style="background-color: rgb(102, 255, 255);">ProductThread.list.notify();</strong></span>
}
super.run();
synchronized(list){
//不停执行,生产手机
while(true){
if(list.size()>10){
try {
<strong style="background-color: rgb(51, 255, 255);">list.wait();</strong>
} catch (InterruptedException e) {
e.printStackTrace();
}
}
MiPhone mp = new MiPhone();
mp.setName("小米"+count);
count++;
//把生产出来的手机添加到仓库list中
list.add(mp);
System.out.println("生产商,生产了一个小米手机,手机型号是:"+mp.getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
<strong style="background-color: rgb(51, 255, 255);">//提醒消费者,手机已经生产完成,可以进行销售
list.notify();</strong>
}
需要注意的是1、
wait和notify必须在同步锁之内使用2、同步锁锁定对象和wait、notify对象必须同一个
3、当对象wait挂起状态时候是会释放同步锁的