Java线程同步

来源:互联网 发布:云势软件 张英男 编辑:程序博客网 时间:2024/05/22 18:24

问题引出

如若CPU是单核则不存在线程同步问题

        new Thread(new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                for(int i = 0; i < 20 ; i ++)                Log.i("qiansheng", "thread1");            }        }).start();        new Thread(new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                for(int i = 0; i < 20 ; i ++)                Log.i("qiansheng", "thread2");            }        }).start();

结果输出:
09-14 09:54:59.491 14233-15603/com.example.threadtest I/qiansheng: thread2
09-14 09:54:59.491 14233-15602/com.example.threadtest I/qiansheng: thread1
09-14 09:54:59.491 14233-15603/com.example.threadtest I/qiansheng: thread2
09-14 09:54:59.491 14233-15602/com.example.threadtest I/qiansheng: thread1
09-14 09:54:59.491 14233-15603/com.example.threadtest I/qiansheng: thread2
09-14 09:54:59.492 14233-15602/com.example.threadtest I/qiansheng: thread1
09-14 09:54:59.492 14233-15603/com.example.threadtest I/qiansheng: thread2
09-14 09:54:59.492 14233-15602/com.example.threadtest I/qiansheng: thread1
09-14 09:54:59.492 14233-15603/com.example.threadtest I/qiansheng: thread2
09-14 09:54:59.492 14233-15602/com.example.threadtest I/qiansheng: thread1
09-14 09:54:59.492 14233-15603/com.example.threadtest I/qiansheng: thread2
09-14 09:54:59.492 14233-15603/com.example.threadtest I/qiansheng: thread2
线程五种状态:
创建: 当用new操作符创建一个线程时, 例如new Thread(r)
就绪:调用start(),等待分配时间片
运行:run();
阻塞:线程通过调用sleep方法进入睡眠状态、线程试图得到一个锁,而该锁正被其他线程持有(wait)…暂时退出运行状态
死忙:run()结束或异常结束;
这里写图片描述
sleeping->ready-to-run有问题!!!

这里写图片描述

生产者&消费者

主要通过对缓冲区加锁,然后适时执行wait、notify即可。

public class ProducerActivity extends Activity{    private List list;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_producer);        list = new ArrayList<Integer>();        Log.d("qiansheng", "list size:" + list.size());        //生产者        new Thread(new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                while(true) {                    synchronized (list) {                        while(list.size() >= 6) {                            try {                                list.wait();                            } catch (InterruptedException e) {                                // TODO Auto-generated catch block                                e.printStackTrace();                            }                        }                        list.add((list.size()));                        Log.i("qiansheng", "生产了:" + (list.size() - 1));                        list.notifyAll();                    }                }            }        }).start();        //消费者        new Thread(new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                while(true) {                    synchronized (list) {                        while(list.size() == 0) {                            try {                                list.wait();                            } catch (InterruptedException e) {                                // TODO Auto-generated catch block                                e.printStackTrace();                            }                        }                        list.remove((list.size() - 1));                        Log.i("qiansheng", "消费了:" + (list.size()));                        list.notifyAll();                    }                }            }        }).start();    }}

哲学家就餐问题

public class ZhexuejiaActivity extends Activity {    public Kuaizi[] kuaizis = new Kuaizi[5];    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_zhexuejia);        for (int i = 0; i < 5; i ++){            kuaizis[i] = new Kuaizi();        }        ExecutorService exe = Executors.newCachedThreadPool();        for (int i = 0; i < 5; ++i){            Zhexuejia zhexuejia = null;            if(i < 4) {                zhexuejia = new Zhexuejia(kuaizis[i], kuaizis[i + 1], i);            } else {                zhexuejia = new Zhexuejia(kuaizis[0], kuaizis[i], i);            }            exe.execute(zhexuejia);        }    }}class Kuaizi{    boolean isTaked = false;    public void take(){        synchronized (this) {            while(isTaked){                try {                    this.wait();                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            isTaked = true;            this.notifyAll();        }    }    public void drop(){        synchronized (this) {            if (isTaked){                isTaked = false;                this.notifyAll();            }        }    }}class Zhexuejia implements Runnable{    public Kuaizi left;    public Kuaizi right;    public int id;    public Zhexuejia(Kuaizi left, Kuaizi right, int id){        this.left = left;        this.right = right;        this.id = id;    }    public void eat(){        left.take();        right.take();        Log.i("qiansheng", "The" + id + "is eated!");    }    public void think(){        left.drop();        right.drop();        Log.i("qiansheng", "The" + id + "is think");    }    @Override    public void run() {        // TODO Auto-generated method stub        while(true){            eat();            think();        }    }}

读者写者问题

public class DuzheActivity extends Activity{    private Semaphore wmutex;    private Semaphore rmutex;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        wmutex = new Semaphore(1); //两个读者,互斥        rmutex = new Semaphore(5);        setContentView(R.layout.activity_duzhe);//      ExecutorService exe = Executors.newCachedThreadPool();        for(int i = 0; i < 5; i ++){//          exe.execute(new Reader());            new Thread(new Reader()).start();        }        for(int i = 0; i < 2; ++i){//          exe.execute(new Writer());            new Thread(new Writer()).start();        }    }    class Reader implements Runnable{        public void read(){            try {                wmutex.acquire(); //写者不能再写了                rmutex.acquire();                Log.d("qiansheng", "This thread:" + Thread.currentThread() + "is reading");                Thread.sleep(300);                wmutex.release();                rmutex.release();            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        @Override        public void run() {            // TODO Auto-generated method stub            read();        }    }    class Writer implements Runnable{        public void write(){            try {                wmutex.acquire();                rmutex.acquire(5);                Log.d("qiansheng", "This thread:" + Thread.currentThread() + "is write");                Thread.sleep(3000);                wmutex.release();                rmutex.release(5);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        @Override        public void run() {            // TODO Auto-generated method stub            write();        }    }}
0 0
原创粉丝点击