题目:请编写一个多线程程序,实现两个线程,其中一个线程完成对某个对象的int成员变量的增加操作,即每次加1,另一个线程完成对该对象的成员变量的减操作,即每次减1,同时要保证该变量的值不会小于0,不会大于1,该变量的初始值为0.
即要求输出结果是0101010101010101这样的形式
关于wait,notify,notifyAll以及sleep方法的关系(重点)
1 如果一个线程调用了某个对象的wait方法,那么该线程首先必须要有该对象的锁(换句话说,一个线程调用了某个对象的wait方法,你们该wait方法必须要在synchronized中)
2 如果一个线程调用了某个对象的wait方法,那么该线程就会释放该对象的锁
3 在java对象中,有两种池(锁池,等待池)
4 如果一个线程调用了某个对象的wait方法,那么该线程进入该对象的等待池中(释放锁),如果未来的某一时刻,另外一个线程调用了相同的对象的notify或notifyall方法,那么在该等待池中的等待的线程就会起来进入该对象的锁池中,去等待获得该对象的锁,如果获得锁成功后,那么该线程将继续沿着wait方法之后的路径去执行。
5 sleep(long time),如果一个线程调用了sleep方法睡眠,那么在睡眠的同时,它不会失去对象的锁的拥有权。
关于synchronized关键字的作用
1 在某个对象的所有synchronized方法中,在某一时刻,只能有一个唯一的一个线程去访问这些synchronized方法
2 如果一个方法是synchronized方法,那么该synchronized关键字表示给当前对象上锁(即this)
3 如果一个synchronized方法是静态的(static的),那么该synchronized关键字表示给当前对象所对应的Class对象上锁。(每个类,不管生成多少对象,其Class对象只有一个)
代码示例一、
- package com.test.thread;
- public class Sample {
- private int number;
- public synchronized void increate()
- {
- while(number>0)
- {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- number++;
- System.out.println(number);
- notify();
- }
- public synchronized void decreate()
- {
- while(number==0)
- {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- number--;
- System.out.println(number);
- notify();
- }
- }
- package com.test.thread;
- public class IncreateThread extends Thread {
- private Sample sample;
- public IncreateThread(Sample sample)
- {
- this.sample = sample;
- }
- @Override
- public void run() {
- for(int i=0;i<5;i++)
- {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- sample.increate();
- }
- }
- }
- package com.test.thread;
- public class DecreateThread extends Thread {
- private Sample sample;
- public DecreateThread(Sample sample)
- {
- this.sample = sample;
- }
- @Override
- public void run() {
- for(int i=0;i<5;i++)
- {
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- sample.decreate();
- }
- }
- }
- package com.test.thread;
- public class TestThread {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Sample sample = new Sample();
- Thread thread1 = new IncreateThread(sample);
- Thread thread2 = new DecreateThread(sample);
- Thread thread3 = new IncreateThread(sample);
- Thread thread4 = new DecreateThread(sample);
- thread1.start();
- thread2.start();
- thread3.start();
- thread4.start();
- }
- }