Java笔记3 多线程<2>线程间通信-代码分析以及多线程常见方法的运用

来源:互联网 发布:mac文件夹加密怎么解除 编辑:程序博客网 时间:2024/05/20 01:13

------- android培训、java培训、期待与您交流! ----------

第12天-01-多线程(线程间通信-示例代码)

/*

线程间通讯:

其实就是多个线程在操作同一个资源,

但是操作的动作不同。

 

*/

class Res{         

    String name;

    String sex;

    boolean flag = false;

}

 

class Input implements Runnable{

    private Resr ;

    Input(Res r){

       this.r = r;

    }

    public void run(){

       int x = 0;

       while(true){

              if(r.flag)

                  try{r.wait();}catch(Exception e){}

              if(x==0){

                  r.name="mike";

                  r.sex="man";

              }

              else{

                  r.name="丽丽";

                  r.sex ="女女女女女";

              }

              x = (x+1)%2;

              r.flag =true;

              r.notify();

       }

    }

}

 

class Output implements Runnable{

    private Resr ;

   

    Output(Res r){

       this.r = r;

    }

    public void run(){

       while(true){

              if(!r.flag)

                  try{r.wait();}catch(Exception e){}

              System.out.println(r.name+"...."+r.sex);

              r.flag =false;

              r.notify();

       }

    }

}

 

 

class  InputOutputDemo

{

    public static void main(String[] args)

    {

       Res r = new Res();

 

       Input in = new Input(r);

       Output out = new Output(r);

 

       Thread t1 = new Thread(in);

       Thread t2 = new Thread(out);

 

       t1.start();

       t2.start();

    }

}

运行结果:


运行结果有名字跟性别对不上的情况出现。

 

 

第12天-02~03多线程(线程间通信-解决安全问题~等待唤醒机制)

对上一个代码上同步锁,问题可以得到解决。下面代码还加入了等待唤醒功能。

class Res{

    String name;

    String sex;

    boolean flag = false;

}

 

class Input implements Runnable{

    private Resr ;

    Input(Res r){

       this.r = r;

    }

    public void run(){

       int x = 0;

       while(true){

           synchronized(r){//上同步锁

              if(r.flag)

                  try{r.wait();}catch(Exception e){}

              if(x==0){

                  r.name="mike";

                  r.sex="man";

              }

              else{

                  r.name="丽丽";

                  r.sex ="女女女女女";

              }

              x = (x+1)%2;

              r.flag =true;

              r.notify();

           }

       }

    }

}

 

class Output implements Runnable{

    private Resr ;

   

    Output(Res r){

       this.r = r;

    }

    public void run(){

       while(true){

           synchronized(r){//上同步锁

              if(!r.flag)

                  try{r.wait();}catch(Exception e){}

              System.out.println(r.name+"...."+r.sex);

              r.flag =false;

              r.notify();

           }

       }

    }

}

 

 

class  InputOutputDemo

{

    public static void main(String[] args)

    {

       Res r = new Res();

 

       Input in = new Input(r);

       Output out = new Output(r);

 

       Thread t1 = new Thread(in);

       Thread t2 = new Thread(out);

 

       t1.start();

       t2.start();

    }

}

/*

wait:

notify();

notifyAll();

 

都使用在同步中,因为要对持有监视器()的线程操作。

所以要使用在同步中,因为只有同步才具有锁。

 

为什么这些操作线程的方法要定义Object类中呢?

因为这些方法在操作同步中线程时,都必须要标识它们所操作线程只有的锁,

只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒。

不可以对不同锁中的线程进行唤醒。

 

也就是说,等待和唤醒必须是同一个锁。

 

而锁可以是任意对象,所以可以被任意对象调用的方法定义Object类中。

 

*/

 

 

12天-04-多线程(线程间通信-代码优化)

class Res{

    private Stringname;

    private Stringsex;

    private boolean flag = false;

 

    public synchronized void set(String name,String sex){//将同步代码封装在一个方法中。同步方法是用的是this

       if(flag)

           try{this.wait();}catch(Exception e){}

      

       this.name = name;

       this.sex = sex;

       flag = true;

       this.notify();

    }

    public synchronized void out(){

       if(!flag)

           try{this.wait();}catch(Exception e){}

       System.out.println(name+"........"+sex);

       flag = false;

       this.notify();

    }

}

 

class Input implements Runnable{

    private Resr ;

    Input(Res r){

       this.r = r;

    }

    public void run(){

       int x = 0;

       while(true){

           if(x==0)            

              r.set("mike","man");           

           else  

              r.set("丽丽","女女女女女");             

           x = (x+1)%2;

       }

    }

}

 

class Output implements Runnable{

    private Resr ;

   

    Output(Res r){

       this.r = r;

    }

    public void run(){

       while(true){

           r.out();

       }

    }

}

 

class  InputOutputDemo{

    public static void main(String[] args) {

       Res r = new Res();

 

       new Thread(new Input(r)).start();

       new Thread(new Output(r)).start();

       /*

       Input in = new Input(r);

       Output out = new Output(r);

 

       Thread t1 = new Thread(in);

       Thread t2 = new Thread(out);

 

       t1.start();

       t2.start();

       */

    }

}

 

 

第12天-05-多线程(线程间通信-生产者消费者)

代码示例:

 

/*

 * 生产一个消费一个的代码(此程序如果只启动两个线程(一个生产一个消费,能打印出

 * 一生产一消费来,如果多于一个线程就可能出现生产一个商品,消费多个商品的情况,

 * 或生产多个商品,消费一个商品(这是不允许的)))

 * */

class ProducerConsumerDemo {

    public static void main(String[] args) {

       Resource r = new Resource();

 

       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();

 

    }

}

 

/*

对于多个生产者和消费者。

为什么要定义while判断标记。

原因:让被唤醒的线程再一次判断标记。

 

 

为什么定义notifyAll

因为需要唤醒对方线程。

因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。

 

*/

 

 

class Resource{

    private Stringname;

    private int count = 1;

    private boolean flag = false;

           //  t1   t2

    public synchronized void set(String name){   

       if(flag)

       //while(flag)//改进后的代码1)

           //t1(放弃资格)  t2(获取资格)

           try{this.wait();}catch(Exception e){}//代码块<1>try~e){}

      

       this.name = name+"--"+count++;//代码块<2>this.name~this.notify();

       System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);

       flag = true;

       this.notify();

       //this.notifyAll();//改进后的代码2)

    }

 

 

    // t3   t4 

    public synchronized void out(){

       if(!flag)

       //while(!flag)//改进后的代码3)

           //t3(放弃资格) t4(放弃资格)

           try{wait();}catch(Exception e){}//代码块<3>

       //代码块<4>System~this.notifyAll();

       System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);

       flag = false;

       this.notify();

       //this.notifyAll();//改进后的代码4)

    }

}

 

class Producerimplements Runnable{

    private Resourceres;

 

    Producer(Resource res){

       this.res = res;

    }

    public void run(){

       while(true){

           res.set("+商品+");

       }

    }

}

 

class Consumerimplements Runnable{

    private Resourceres;

 

    Consumer(Resource res){

       this.res = res;

    }

    public void run(){

       while(true){

           res.out();

       }

    }

}

/*

解析(注:在代码中已注明<1><2><3><4>):

生产t1t2,消费t3t4(刚开始生产者先获取cpu执行权)

为了简化设 flag = false:(1) flag = true:(2)

cpu执行权:(3);无cpu执行权:(4);跳过wait()向下执行:(5)

 

 1)t1 -(1)-> (5) --> (2),notify();//唤醒一个线程  -(3)(2)-> t1.wait();

 -->t1放弃资格(其他三个线程竞争(3))

 

 2)假设t2抢到(3),:t2 -(2)->t2.wait() -->t2弃权,t3获得执行权.

 t3 -(!2)-> (5) --> flag =false;notify();//注意此时t1可能醒,但是不一定(3)

 -(3)(!1)->t3.wait() --> t3弃权(此时t1t4有竞争(3)的行为)

 

 3)假设t4竞争到cpu执行权,则t4 -(!1)-> t4.wait() --> t4(弃权) -->t1获权(t2

 t3t4弃权中)

 

 4)t1执行<4> -(3)(2)-> t1.wait();//t1弃权,此时,线程池中t2先进去的,把t2唤醒,

 此时(t1t3t4弃权中,无获权资格),t2获权,t2从代码块<2>开始执行(此时 flag = true),

 但是此时t2没有判断就从<2>起始处开始运行,生产打印一次,flag = true ,t3唤醒 -(3)(2)->

 t2.wait() -->....(重复以上步骤)

 

*/

/*

 改进后的代码已漂珠在源程序中,

 (1)if语句改为while语句

 (2)notify();改为notifyAll();

 */

 

 

第12天-06-多线程(线程间通信-生产者消费者JDK5.0升级版)

代码如下:

import java.util.concurrent.locks.*;

 

class ProducerConsumerDemo2 {

    public static void main(String[] args) {

       Resource r = new Resource();

 

       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();

 

    }

}

 

/*

JDK1.5 中提供了多线程升级解决方案。

将同步Synchronized替换成现实Lock操作。

Object中的waitnotify notifyAll,替换了Condition对象。

该对象可以Lock进行获取。

该示例中,实现了本方只唤醒对方操作。

 

Lock:替代了Synchronized

    lock

    unlock

    newCondition()

 

Condition:替代了Object wait notify notifyAll

    await();

    signal();

    signalAll();

*/

class Resource{

    private Stringname;

    private int count = 1;

    private boolean flag = false;

           //  t1   t2

    private Locklock =new ReentrantLock();

 

    private Conditioncondition_pro =lock.newCondition();

    private Conditioncondition_con =lock.newCondition();

 

 

 

    public  void set(String name)throws InterruptedException{

       lock.lock();

       try{

           while(flag)

              condition_pro.await();//t1,t2

           this.name = name+"--"+count++;

 

           System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);

           flag = true;

           condition_con.signal();

       }finally{

           lock.unlock();//释放锁的动作一定要执行。

       }

    }

 

 

    // t3   t4 

    public  void out()throwsInterruptedException{

       lock.lock();

       try{

           while(!flag)

              condition_con.await();

           System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);

           flag = false;

           condition_pro.signal();

       }finally{

           lock.unlock();

       }

      

    }

}

 

class Producerimplements Runnable{

    private Resourceres;

 

    Producer(Resource res){

       this.res = res;

    }

    public void run(){

       while(true){

           try{

              res.set("+商品+");

           }

           catch (InterruptedException e){

           }

          

       }

    }

}

 

class Consumerimplements Runnable{

    private Resourceres;

 

    Consumer(Resource res){

       this.res = res;

    }

    public void run(){

       while(true){

           try{

              res.out();

           }

           catch (InterruptedException e){

           }

       }

    }

}

 

 

12天-07-多线程(停止线程)

代码演示:

/*

stop方法已经过时。

 

如何停止线程?

只有一种,run方法结束。

开启多线程运行,运行代码通常是循环结构。

 

只要控制住循环,就可以让run方法结束,也就是线程结束。

 

特殊情况:

当线程处于了冻结状态。

就不会读取到标记。那么线程就不会结束。

 

当没有指定的方式让冻结的线程恢复到运行状态是,这时需要对冻结进行清除。

强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。

 

Thread类提供该方法 interrupt();

*/

class StopThreadimplements Runnable{

    private boolean flag =true;

    public  synchronized void run(){

       while(flag){ 

           try {

              wait();

           } catch (InterruptedException e) {

              System.out.println(Thread.currentThread().getName()+"....Exception");

           }

           System.out.println(Thread.currentThread().getName()+"....run");

       }

    }

    public void changeFlag(){

       flag = false;

    }

}

 

 

public class  StopThreadDemo{

    public static void main(String[] args) {

       StopThread st = new StopThread();

      

       Thread t1 = new Thread(st);

       Thread t2 = new Thread(st);

 

       //t1.setDaemon(true);

       //t2.setDaemon(true);

       t1.start();

       t2.start();

 

       int num = 0;

 

       while(true){

           if(num++ == 60){

              st.changeFlag();//<1>

              t1.interrupt();//<2>

              t2.interrupt();//<3>

              break;

           }

           System.out.println(Thread.currentThread().getName()+"......."+num);

       }

       System.out.println("over");

    }

}

/*

在未去掉去掉<2><3>处注释前的运行结果(程序并未结束):

去掉<2><3>处的注释后的运行结果:

*/

 

第12天-08-多线程(守护线程)

l  public final void setDaemon(boolean on)

将该线程标记为守护线程或用户线程,当正在运行的线程都是守护线程时,Java虚拟机退出。

该方法必须在启动线程前调用(也就是在使用start()方法前调用)。

该方法先调用该线程的checkAccess方法,且不带任何参数。这时可能抛出Secu

rityException(在当前线程中)。

 

 

第12天-09-多线程(Join方法)

代码演示:

/*

join:

A线程执行到了B线程的.join()方法时,A就会等待。等B线程都执行完,A才会执行。

 

join可以用来临时加入线程执行。

 

 

*/

 

class Demo implements Runnable{

    public void run(){

       for(int x=0; x<70; x++){

           System.out.println(Thread.currentThread().toString()+"....."+x);

           //Thread.yield();

       }

    }

}

 

 

public class  JoinDemo{

    public static void main(String[] args)throws Exception{

        Demo d = new Demo();

       Thread t1 = new Thread(d);

       Thread t2 = new Thread(d);

       t1.start();

      

       //t1.setPriority(Thread.MAX_PRIORITY);

 

       //t1.join();//<1>

       t2.start();

       t1.join();//<2>

 

       for(int x=0; x<80; x++)

       {

           System.out.println("main....."+x);

       }

       System.out.println("over");

    }

}

/*

 结果分析:

 (1)注释<2>、去掉注释行<1>,打印结果:t1执行完后,t2main才会交替执行

 (2)注释<1>、去掉注释行<2>,打印结果:t1t2交替执行一会后,t2要等t1执行完毕,

 才会和main交替执行。

 */

 

 

第12天-10-多线程(优先级&yield方法)

l  线程的优先级共10级

l  设置线程优先级举例:

t1.setPriority(Thread.MAX.PRIORITY);

l  public static void yield()

暂停当前正在执行的线程对象,并执行其他线程。

 

 

------- android培训、java培训、期待与您交流! ----------