本帖最后由 136616244 于 2014-5-8 21:36 编辑
下面的代码有的机子上会出现死锁,有的机子不会出现- package 多线程;
- class 生产者消费者 {
- public static void main(String[] args) {
- Res r = new Res();
- boolean flag = false;
- Producer p = new Producer(r);
- Consumer c = new Consumer(r);
- Thread t = new Thread(p);
- Thread t2 = new Thread(c);
- t.start();
- t2.start();
- }
- }
- class Res{
- boolean flag = false;
- int count = 0;
- public synchronized void setResource(){
- count++;
- System.out.println(Thread.currentThread().getName()+"生产者------"+count);
- }
- public synchronized void getResource(){
- System.out.println(Thread.currentThread().getName()+"消费者。。。。。。。。。。。。"+count);
- }
- }
- class Producer implements Runnable{
- Res r;
- Producer(Res r ){
- this.r = r;
- }
- public void run(){
- while(true){
- if(!(r.flag)){
- r.setResource();
- r.flag =true;
- }
- }
- }
- }
- class Consumer implements Runnable{
- Res r;
- Consumer(Res r){
- this.r = r;
- }
- public void run(){
- while(true){
- if(r.flag){
- r.getResource();
- r.flag =false;
- }
- }
- }
- }
复制代码
,为啥呢? |