1 线程共享内存
每个线程表示一条单独的执行流,有自己的程序计数器,有自己的栈,但线程之间可以共享内存,它们可以访问和操作相同的对象。
import java.util.ArrayList;
import java.util.List;
public class ShareMemoryDemo
{
//静态变量
private static int shared = 0;
private static void incrShared()
{
shared++;
}
//静态内部类
//静态内部类不可以访问外部类的实例变量
//但是可以访问外部类的类变量
public static class ChildThread extends Thread
{
List<String> list;
public ChildThread(List<String> list )
{
this.list = list;
}
public void run()
{
incrShared();
list.add(Thread.currentThread().getName());
}
}
public static void main(String[] args) throws InterruptedException
{
List<String> list = new ArrayList<String>();
ChildThread t1 = new ChildThread(list);
ChildThread t2 = new ChildThread(list);
//启动两个线程
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(shared);
System.out.println(list);
}
}
代码分析:
1)有三条执行流,一条执行main方法,另外两条执行ChildThread的run方法。
2)不同执行流可以访问和操作相同的变量,如程序中的shared和list变量,但是注意shared和list不是共享变量。
3)当多条执行流执行相同的程序代码时,每条执行流都有单独的栈,方法中的参数和局部变量都有自己的一份。
代码示例: 多个线程同时访问一个数据
public class CounterThread extends Thread
{
//counter是一个共享变量
private static int counter = 0;
//每个线程对counter循环加1000次
public void run()
{
for(int i=0;i<1000;i++)
{
counter++;
}
}
public static void main(String[] args) throws InterruptedException
{
int num =1000;
//创建一个Thread[]类型的数组,数组长度为1000
Thread[] threads = new Thread[num];
for(int i=0;i<num;i++)
{
//循环创建并启动1000个线程
threads[i]=new CounterThread();
threads[i].start();
}
for(int i=0;i<num;i++)
{
threads[i].join();
}
//main线程等待所有线程结束后输出counter值
System.out.println(counter);
}
}
代码分析:
线程执行体中有一个共享变量counter,在main方法中循环创建了1000个线程
每个线程执行run()方法,对counter循环加1000次,面方法等待所有线程结束胡输出counter的值。
结果分析:
期望的值为100万,但是结果不是,原因是在这1000个线程中可能会有两个以上的线程同时取到相同的counter值,比如都取到了100,第一个线程执行完以后为101,第二个线程执行完以后也为101,最终结果与期望不符。
2 synchronized的用法和原理
2.1 synchronized用于实例方法
对于实例方法加了synchronized,保护的是实例对象,监事器为this代表的对象
代码示例:
保证同一时刻只有一个线程可以执行同一个synchronized实例方法
public class Counter
{
private int count;
//因为counter是一个共享变量,所以将它所在的方法加锁
public synchronized void incr()
{
count++;
}
public synchronized int getCounter()
{
return count;
}
}
public class CounterThread extends Thread
{
Counter counter;
public CounterThread(Counter counter)
{
this.counter = counter;
}
public void run()
{
for(int i=0;i<1000;i++)
{
counter.incr();
}
}
public static void main(String[] args) throws InterruptedException
{
int num =1000;
//对象应该放在局部的位置创建
Counter counter = new Counter();
//创建一个Thread[]类型的数组
Thread[] threads = new Thread[num];
for(int i=0;i<num;i++)
{
//循环创建并启动1000个线程
threads[i]=new CounterThread(counter);
threads[i].start();
}
//main线程等待所有线程结束后输出counter值
for(int i=0;i<num;i++)
{
threads[i].join();
}
System.out.println(counter.getCounter());
}
}
多个线程是可以同时执行同一个synchronized实例方法的,只要它们访问的对象是不同的即可
例如:
Counter counter1 = new Counter();
Counter counter2 = new Counter();
Thread t1 = new CounterThread(counter1);
Thread t2 = new CounterThread(counter2);
t1和t2两个线程是可以同时执行Counter的incr方法,因为它们访问的是不同的Counter对象,一个是counter1,另一个是counter2。
所以,synchronized实例方法实际保护的是同一个对象的方法调用,确保同时只能有一个线程执行。
执行synchronized实例方法的流程
1)尝试获得锁,如果能够获得锁,继续下一步,否则加入等待队列,阻塞并等待唤醒。
2)执行实例方法体代码。
3)释放锁,如果等待队列上有等待的线程,从中取一个并唤醒,如果有多个等待的线程,唤醒哪一个是不一定的,不保证公平性。
synchronized保护的是对象而非代码,只要访问的是同一个对象的synchronized方法,即使是不同的代码,也会被同步。
2.2 synchrozied用于静态方法
对实例方法,保护的是当前实例对象this,对静态方法,保护的是是类对象,这里是StaticCounter.class。
public class StaticCounter
{
private static int count = 0;
public static synchronized void incr()
{
count++;
}
public static synchronized int getCount()
{
return count++;
}
}
2.4 synchronized用于代码块
synchronized代码块修饰Counter类
代码示例:
public class Counter
{
private int count;
public void incr()
{
synchronized(this)
{
count++;
}
}
public int getCount()
{
synchronized(this)
{
return count;
}
}
}
synchronized代码块修饰StaticCounter类
代码示例:
public class StaticCounter
{
private static int count;
public void incr()
{
synchronized(StaticCounter.class)
{
count++;
}
}
public int getCount()
{
synchronized(StaticCounter1.class)
{
return count;
}
}
}
synchronized同步的对象可以是任意对象,任意对象都有一个锁和等待队列,或者说,任何对象都可以作为锁对象。
代码示例:
public class Counter2
{
private int count;
private Object obj = new Object();
public void incr()
{
synchronized(obj)
{
count++;
}
}
public int getCount()
{
synchronized(obj)
{
return count;
}
}
}
2.5 死锁
使用synchronized或者其他锁,要注意死锁。所谓死锁就是类似这种现象,比如,有a、b两个线程,a持有锁A,在等待锁B,而b持有锁B,在等待锁A, a和b陷入了互相等待,最后谁都执行不下去。
public class DeadLockDemo
{
private static Object lockA = new Object();
private static Object lockB = new Object();
public static void startThreadA()
{
//创建一个内部类,即Thread类的子类对象
Thread aThread = new Thread(){
/*
*线程1执行run()方法时,持有了A锁
*接着执行sleep()方法,线程1进入阻塞状态,让CPU执行另一个线程
*紧接着线程2执行run()方法,持有了B锁
*接着执行sleep()方法,线程进入阻塞状态
*线程1醒来想要拿B锁,但是此时线程2还没有释放B锁
*线程2醒来想要拿A锁,但是此时线程1还没有释放A锁
*所以,线程1和线程2陷入了互相等待对方释放锁的过程。
*/
//在内部类中重写run()方法
public void run()
{
synchronized(lockA)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
synchronized(lockB)
{
}
}
};
//使用这个线程对象启动线程
aThread.start();
}
public static void startThreadB()
{
Thread bThread = new Thread(){
public void run()
{
synchronized(lockB)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
synchronized(lockA)
{
}
}
};
bThread.start();
}
public static void main(String[] args)
{
startThreadA();
startThreadB();
}
}
3 线程安全问题示例
火车站卖票问题,两个卖票口同时卖相同的100张票,会发生线程安全问题
3.1 火车站卖票为何会产生线程安全问题?
原因:多个线程同时对同一数据进行操作。
class SaleTicket implements Runnable
{
//ticket是共享数据,当有多个线程对其操作时,会产生线程安全问题
private int ticket = 100;
public void run()
{
while(true)
{
if(ticket>0)
{
/*
* 假如说ticket=1
* 首先线程1判断ticket>0,判断出ticket>0以后线程1休眠了10ms
* 在这个线程1休眠的时候,线程2抢到了CPU,判断ticket>0以后线程2进入休眠
* 接着线程1休眠结束,继续向下执行得ticket=0
* 再接着线程2休眠结束,继续向下执行的ticket=-1
* 由此可见出现了错误的票数,因为票数不可能为负数
*/
//这个方法有异常但是不能抛出,因为run方法是覆盖方法
//父类被覆盖的方法没有抛出异常,所以子类覆盖方法就不能抛出异常,
//因此只能显示的捕捉异常
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..."+ticket--);
}
}
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
SaleTicket t = new SaleTicket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}
3.2 如何解决这个问题?
- 解决的思想:
只要保证多条操作共享数据的代码在某一时间段,被一条线程所执行,在执行期间不允许其他线程参与运算。 - 解决方法:加入同步
- 同步的前提:多个线程在同步中必须使用同一个锁,这才是对多个线程同步
3.2.1 选择加入同步代码块解决
代码:
class SaleTicket implements Runnable
{
private int ticket = 100;
Object obj = new Object();
public void run()
{
while(true)
{
//同步代码块
//对象可以随意,什么都行,最好找个找个现成的类,不用创建这个类了
//obj对象就是同步监视器,这个对象推荐使用共享资源所在的类
synchronized(obj)
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..."+ticket--);
}
}
}
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
SaleTicket t = new SaleTicket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}
3.2.1.1 思考上个程序中同步代码块的监视器可以为this吗?
可以加入this,下面来看两个代码对比来理解这个问题:
代码1:
class SaleTicket implements Runnable
{
private int ticket = 100;
public void run()
{
while(true)
{
synchronized(this)
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..."+ticket--);
}
}
}
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
//定义两个SaleTicket对象
SaleTicket t1 = new SaleTicket();
SaleTicket t2 = new SaleTicket();
Thread t3 = new Thread(t1);
Thread t4 = new Thread(t2);
t3.start();
t4.start();
}
}
在上面程序中,Thread-0和Thread-1两个线程可以同时执行un()方法中的同步代码块,因为它们访问的是不同的SaleTicket对象,一个是t1,另一个是t2。也就是说是两个不同的监视器对象
对比代码:代码2
作为代码1的对比,只修改代码1的主函数就可以
public class ThreadDemo
{
public static void main(String[] args)
{
SaleTicket t = new SaleTicket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}
Thread-0和Thread-1两个线程不能同时访问run()方法中的同步代码块,因为他们的监视器是同一个对象,this代表的两个对象为同一个SaleTicket对象t 。起到了同步的作用,所以可以用this作为监视器
注意,调用run()方法的是SaleTicket对象,只要这两个对象为同一个,就可以起到同步的作用。
3.2.1.2 加入了同步机制,仍然出现线程安全问题,为什么?
说明没有遵守同步的前提。
同步的前提:多个线程在同步中必须使用同一个锁,这才是对多个线程同步
只有需要同步的代码才同步,不需要同步的代码不用同步
class SaleTicket1 implements Runnable
{
private int ticket = 100;
public void run()
{
while(true)
{
//注意这里的监视器对象是new出来的,也就是说每个线程有自己的监视器
//多个线程使用的不是同一个监视器,不能起到同步的作用
synchronized(new Object())
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..."+ticket--);
}
}
}
}
}
public class ThreadDemo2
{
public static void main(String[] args)
{
SaleTicket1 t = new SaleTicket1();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}
3.2.2 选择同步函数解决
3.2.2.1 同步实例方法
将同步synchronized加在实例方法上,同步方法是实例方法,所以锁对象为this
class Bank
{
private int sum;
public synchronized void add(int n)
{
sum = sum+n;
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("sum="+sum);
}
}
class Customer implements Runnable
{
private Bank b = new Bank();
public void run()
{
for(int x=0;x<3;x++)
{
b.add(100);
}
}
}
public class ThreadTest
{
public static void main(String[] args)
{
Customer c = new Customer();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
3.2.2.2 验证同步实例方法的监视器对象为this
- 启动两个线程:
一个线程负责执行同步代码块(监视器为明锁)
另一个线程使用同步函数(监视器为this) - 两个线程执行的任务都是卖票,如果他们没有使用相同的锁,说明他们没有同步,会出现数据错误
- 问题:怎么能让一个线程一直在同步代码块中,一个线程在同步函数中呢?
可以通过切换的方式,定义一个标记标量
class SaleTicket implements Runnable
{
private int ticket = 100;
//定义一个boolean的标记
boolean flag= true;
Object obj = new Object();
public void run()
{
//如果标记为true,继续向下执行
if(flag)
{
while(true)
{
//线程Thread-0的监视器为Object对象
synchronized(obj)
{
if(ticket>0)
{
//Thread-0睡眠10ms,cpu切换执行了另一个线程即主线程
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Thread-0醒来后向下执行,ticket--
System.out.println(Thread.currentThread().getName()+"...code..."+ticket--);
}
}
}
}
//标记为false时
else
{
while(true)
//调用sale()方法,而sale()方法为同步方法
//它的监视器对象为SaleTicket对象
sale();
}
}
//在进入sale()方法之前,会对SaleTicket对象加锁
public synchronized void sale()
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...function..."+ticket--);
}
}
}
public class ThreadDemo
{
public static void main(String[] args) throws InterruptedException
{
SaleTicket t = new SaleTicket();
//创建两个线程对象
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
//启动一个线程,执行run()方法,
//标记为true,执行if语句中的同步代码块
t1.start();
//继续向下执行,主线程睡眠10ms
//在主线程醒来之前,Thread-0已经醒来了
Thread.sleep(10);
//主函数醒来向下执行,标记改为false
t.flag = false;
//启动线程Thread-1,执行run()方法
//标记为false,执行else语句中的同步方法
t2.start();
}
}
由于两个线程使用的不是同一格监视器对象,所以出现了线程安全问题,如果将同步代码块中的监视器对象改为this,就会出现正确的结果,说明同步函数的监视器对象为this。
3.2.2.3 同步类方法
如果同步函数被静态修饰呢?那么静态同步函数的锁是什么呢?
static随着类加载,这时不一定有该类的对象,但是一定有一个该类的字节码文件对象
这个对象简单地表示方式为类名.class
class SaleTicket1 implements Runnable
{
//类共享变量
private static int ticket = 100;
//定义一个boolean的标记
boolean flag= true;
Object obj = new Object();
public void run()
{
if(flag)
{
while(true)
{
//监视器为类名.class
synchronized(SaleTicket1.class)
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...code..."+ticket--);
}
}
}
}
else
{
while(true)
sale();
}
}
//监视器对象为类名.class
public static synchronized void sale()
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...function..."+ticket--);
}
}
}
public class ThreadDemo2
{
public static void main(String[] args) throws InterruptedException
{
SaleTicket1 t = new SaleTicket1();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
Thread.sleep(10);
t.flag = false;
t2.start();
}
}
3.2.3 同步嵌套引发的死锁问题
有a、b两个线程,a持有锁A,在等待锁B,而b持有锁B,在等待锁A, a和b陷入了互相等待,最后谁都执行不下去。
代码示例:
class SaleTicket1 implements Runnable
{
private static int ticket = 100;
boolean flag= true;
Object obj = new Object();
public void run()
{
if(flag)
{
while(true)
{
//先用Obj这把锁,再用this这把锁
synchronized(obj)
{
sale();
}
}
}
else
{
//先用this这把锁,再用obj这把锁
while(true)
sale();
}
}
public synchronized void sale()
{
synchronized(obj)
{
if(ticket>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...function..."+ticket--);
}
}
}
}
public class ThreadDemo1
{
public static void main(String[] args) throws InterruptedException
{
SaleTicket1 t = new SaleTicket1();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
Thread.sleep(10);
t.flag = false;
t2.start();
}
}
代码示例:
class Task implements Runnable
{
private boolean flag;
Task(boolean flag)
{
this.flag = flag;
}
public void run()
{
if(flag)
{
synchronized(MyLock.locka)
{
System.out.println("if....a");
synchronized(MyLock.lockb)
{
System.out.println("if...b");
}
}
}
else
{
synchronized(MyLock.lockb)
{
System.out.println("else...b");
synchronized(MyLock.locka)
{
System.out.println("else...a");
}
}
}
}
}
class MyLock
{
public static final Object locka = new Object();
public static final Object lockb = new Object();
}
public class ThreadDemo2
{
public static void main(String[] args)
{
//创建线程任务
Task t1 = new Task(true);
Task t2 = new Task(false);
new Thread(t1).start();
new Thread(t2).start();
}
}
3 线程通信
3.1 线程通信的原理
-
Java的根父类是Object, Java在Object类而非Thread类中定义了一些线程协作的基本方法,即wait()方法和notify()方法
-
wait()方法和notify()方法是如何协作的?
调用wait就会把当前线程阻塞,表示当前线程执行不下去了,它需要等待一个条件,这个条件它自己改变不了,需要其他线程改变。当其他线程改变了条件后,应该调用Object的notify方法。notify做的事情就是从线程池中唤醒一个线程,notifyAll和notify的区别是,它会唤醒线程池中所有的线程。
代码示例:
public class WaitThread extends Thread
{
//协作的条件变量
private boolean fire = false;
public void run()
{
//两个线程都有访问到fire,所以需要加同步保护
synchronized(this)
{
//如果fire为假,就wait()
while(!fire)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("fired");
}
}
//两个线程都有访问到fire,所以需要加同步保护
public synchronized void fire()
{
this.fire = true;
notify();
}
public static void main(String[] args) throws InterruptedException
{
//创建并启动一个线程对象
WaitThread wt = new WaitThread();
wt.start();
//主线程睡眠1s,执行子线程
Thread.sleep(1000);
System.out.println("fire");
//调用同步方法
wt.fire();
}
}
注意:wait和notify方法只能在synchronized代码块或方法内被调用。
划重点
思考一下,如果wait必须被synchronized保护,那一个线程在wait时,另一个线程怎么可能调用同样被synchronized保护的notify方法呢?它不需要等待锁吗?
原因是虽然是在synchronized方法内,但调用wait时,线程会释放对象锁。
wait()和notify()被不同的线程调用,但共享相同的锁和相同对象的synchronized代码块内,它们围绕一个共享的条件变量进行协作
,这个条件变量是程序自己维护的,当条件不成立时,线程调用wait进入阻塞,另一个线程修改了条件变量后调用notify,调用wait的线程唤醒后需要重新检查条件变量。我们在设计多线程协作时,需要想清楚协作的共享变量条件是什么,这是协作的核心
。
3.2 线程通信示例
生产者和消费者:想让生产者生产一个,消费者消费一个
wait():该方法可以让线程处于冻结状态,并将线程临时存储到线程池中
notify():唤醒指定线程池中的任意一个线程
notifyAll():唤醒指定线程池中的任意所有线程
使用这些方法需要注意的问题:
- wait(),notify();notifyAll()必须用在synchronized中
因为他们用来操作同步锁上的线程的状态的 - 使用这些方法时,必须标识他们所属的锁
标识方式为 锁对象.wait() 锁对象.notify() 锁对象.notifyAll() - 相同锁的notify()可以获取相同锁的wait()
持有A锁的线程,被wait()以后,只有A锁的notify才能唤醒
3.2.1 使wait()和notify()产生死锁问题
class Res
{
private String name;
private int count;
//定义标记
private boolean flag;
//提供给商品赋值的方法
public synchronized void set(String name) throws InterruptedException
{
if(flag)
this.wait();//判断结果为true,执行wait()等待,为false就生产
this.name = name+"---"+count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
//生产完毕,将标记改为true
flag = true;
//唤醒消费者
this.notify();
}
//提供一个获取商品的方法
public synchronized void get() throws InterruptedException
{
if(!flag)
this.wait();
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
//将标记改为false
flag=false;
//唤醒生产者
this.notify();
}
}
//生产者
class Producer implements Runnable
{
private Res r;
Producer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.set("面包");
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//消费者
class Consumer implements Runnable
{
private Res r;
Consumer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.get();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ProduceConsumerDemo
{
public static void main(String[] args)
{
//创建资源
Res r = new Res();
//创建两个任务
Producer pro= new Producer(r);
Consumer con = new Consumer(r);
//创建线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}
}
死锁了,所有的线程都处于冻结状态
原因:本方线程在唤醒时,又一次唤醒了本方线程,而本方线程循环判断标记,又继续等待,导致所有的线程都等待了。
3.2.2 如何解决死锁问题
可以使用notifyAll()方法:
所有线程全部唤醒,既有本方线程又有对方线程,但是本方线程唤醒后,会判断标记继续等待,这样对方线程就可以继续执行了。
class Res
{
private String name;
private int count;
//定义标记
private boolean flag;
//提供给商品赋值的方法
public synchronized void set(String name) throws InterruptedException
{
while(flag)//判断结果为true,执行wait()等待,为false就生产
wait();
this.name = name+"---"+count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
//生产完毕,将标记改为true
flag = true;
//唤醒消费者
notifyAll();
}
//提供一个获取商品的方法
public synchronized void get() throws InterruptedException
{
while(!flag)
wait();
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
//将标记改为false
flag=false;
//唤醒生产者
notifyAll();
}
}
//生产者
class Producer implements Runnable
{
private Res r;
Producer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.set("面包");
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//消费者
class Consumer implements Runnable
{
private Res r;
Consumer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.get();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ProduceConsumerDemo
{
public static void main(String[] args)
{
//创建资源
Res r = new Res();
//创建两个任务
Producer pro= new Producer(r);
Consumer con = new Consumer(r);
//创建线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
3.2.3 使用Lock锁
class Res
{
private String name;
private int count;
//创建锁对象
private Lock lock = new ReentrantLock();
//创建和Lock锁绑定的监事器对象
private Condition con = lock.newCondition();
//定义标记
private boolean flag;
//提供给商品赋值的方法
public void set(String name) throws InterruptedException
{
//获取锁
lock.lock();
try
{
while(flag)//判断结果为true,执行wait()等待,为false就生产
//wait();
con.await();
this.name = name+"---"+count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
//生产完毕,将标记改为true
flag = true;
//唤醒消费者
//notifyAll();
con.signalAll();
}
finally
{
//释放锁
lock.unlock();
}
}
//提供一个获取商品的方法
public void get() throws InterruptedException
{
lock.lock();
while(!flag)
//wait();
con.await();
//throw new Exception();
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
//将标记改为false
flag=false;
//唤醒生产者
//notifyAll();
con.signalAll();
lock.unlock();
}
}
//生产者
class Producer implements Runnable
{
private Res r;
Producer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.set("面包");
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//消费者
class Consumer implements Runnable
{
private Res r;
Consumer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.get();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ProduceConsumerDemo
{
public static void main(String[] args)
{
//创建资源
Res r = new Res();
//创建两个任务
Producer pro= new Producer(r);
Consumer con = new Consumer(r);
//创建线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
3.2.3.1 解决效率问题
class Res
{
private String name;
private int count;
//创建锁对象
private Lock lock = new ReentrantLock();
//创建和Lock锁绑定的监事器对象
private Condition producer_con = lock.newCondition();
private Condition consumer_con = lock.newCondition();
//定义标记
private boolean flag;
//提供给商品赋值的方法
public void set(String name) throws InterruptedException
{
//获取锁
lock.lock();
try
{
while(flag)//判断结果为true,执行wait()等待,为false就生产
//wait();
producer_con.await();
this.name = name+"---"+count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
//生产完毕,将标记改为true
flag = true;
//唤醒消费者
//notifyAll();
consumer_con.signalAll();
}
finally
{
//释放锁
lock.unlock();
}
}
//提供一个获取商品的方法
public void get() throws InterruptedException
{
lock.lock();
while(!flag)
//wait();
consumer_con.await();
//throw new Exception();
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
//将标记改为false
flag=false;
//唤醒生产者
//notifyAll();
producer_con.signalAll();
lock.unlock();
}
}
//生产者
class Producer implements Runnable
{
private Res r;
Producer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.set("面包");
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
//消费者
class Consumer implements Runnable
{
private Res r;
Consumer(Res r)
{
this.r = r;
}
public void run()
{
while(true)
try
{
r.get();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ProduceConsumerDemo
{
public static void main(String[] args)
{
//创建资源
Res r = new Res();
//创建两个任务
Producer pro= new Producer(r);
Consumer con = new Consumer(r);
//创建线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}