10 Java基础 多线程2

/*

线程间通讯:

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

但是操作的动作不同

 

*/

class Res

{

         Stringname;

         Stringsex;

}

class Input implements Runnable

{

         privateRes r ;

         Input(Resr)

         {

                   this.r=r;

         }

         publicvoid run()

         {

                   intx=0;

                   while(true)

                   {

                                     synchronized(r)

                            {

                            if(x==0)

                            {

                                     r.name="mike";

                            r.sex="man";

                            }

                            else

                            {

                                     r.name="丽丽";

                            r.sex="女";

                            }

                            x=(x+1)%2;

                            }

                   }

         }

}

class Output implements Runnable

{

         privateRes r ;

         Output(Resr)

         {

                   this.r=r;

         }

         publicvoid run()

         {

                   while(true)

                   {

                                     synchronized(r)//r唯一资源 同一个锁 同步出现安全问题考虑两个前提:是不是多线程 是不是同一个锁

                            {

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

                            }

                   }

         }

}

 

class Inputoutputdemo

{

         publicstatic void main(String[] args)

         {

                   Resr =new Res();

                   Inputin =new Input(r);

                   Outputout=new Output(r);

 

                   Threadt1=new Thread(in);

                   Threadt2=new Thread(out);

 

                   t1.start();

                   t2.start();

                   //System.out.println("HelloWorld!");

         }

}

/*

等待唤醒机制:

notifyAll();全部唤醒

wait(); notify(); notifyAll();

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

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

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

 

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

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

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

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

 

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

 

*/

 

 

class Res

{

         Stringname;

         Stringsex;

         booleanflag=false;

}

class Input implements Runnable

{

         privateRes r ;

         Input(Resr)

         {

                   this.r=r;

         }

         publicvoid run()

         {

                   intx=0;

                   while(true)

                   {

                            synchronized(r)

                            {

                                               if(r.flag)

                                               try{r.wait();}catch(Exceptione){}

                                     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

{

         privateRes r ;

         Output(Resr)

         {

                   this.r=r;

         }

         publicvoid run()

         {

                   while(true)

                   {

                            synchronized(r)//r唯一资源 同一个锁 同步出现安全问题考虑两个前提:是不是多线程 是不是同一个锁

                            {

                                     if(!r.flag)

                                     try{r.wait();}catch(Exceptione){}

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

                                     r.flag=false;

                                     r.notify();

                            }

                   }

         }

}

 

class Inputoutputdemo1

{

         publicstatic void main(String[] args)

         {

                   Resr =new Res();

                   Inputin =new Input(r);

                   Outputout=new Output(r);

 

                   Threadt1=new Thread(in);

                   Threadt2=new Thread(out);

 

                   t1.start();

                   t2.start();

                  

         }

}

/*

将同步synchronized替换成现实lock操作

将Object中wait notify notifyAll 替换了Condition对象

该对象可以对lock锁进行获取

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

 

*/

import java.util.concurrent.locks.*;

class Resource

{

        

         privateString name;

         privateint count=1;

         privateboolean flag=false;

 

         privateLock lock =new ReentrantLock();

        

         privateCondition condition_pro=lock.newCondition();

         privateCondition condition_con=lock.newCondition();

 

 

         public  void set(String name)throwsInterruptedException

         {

                   lock.lock();

                   try

                   {

                            while(flag)//if()只判断一次if条件while每次都判断

                                     condition_pro.await();//t1t2

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

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

                            flag=true;

                            condition_con.signal();

                   }

                   finally

                   {

                            lock.unlock();

                   }

         }

 

         public  void out()throws InterruptedException

         {

                   lock.lock();

                   try

                   {

                   while(!flag)

                   condition_con.await();

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

                   flag=false;

                   condition_pro.signalAll();

                   }

                   finally

                   {

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

                   }

         }

}

 

class Producer implements Runnable

{

         privateResource res ;

          Producer(Resource res)

         {

                   this.res=res;

         }

         publicvoid run()

         {

                   while(true)

                   {

                            try

                            {

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

                            }

                            catch(InterruptedException e)

                            {}

                   }

                  

         }

}

class Consumer implements Runnable

{

         privateResource res ;

          Consumer(Resource res)

         {

                   this.res=res;

         }

         publicvoid run()

         {

                   while(true)

                   {

                            try

                            {

                            res.out();

                            }

                            catch(InterruptedException e)

                            {}

                   }

                  

         }

}

 

 

 

class Lockdemo

{

         publicstatic void main(String[] args)

         {

                   Resourcer =new Resource();

                   Producerpro=new Producer(r) ;

                   Consumercon=new Consumer(r);

 

                   Threadt1=new Thread(pro);

                   Threadt2=new Thread(pro);

                   Threadt3=new Thread(con);

                   Threadt4=new Thread(con);

 

                  

                   t1.start();

                   t2.start();

                   t3.start();

                   t4.start();

         }

}

 

/*

当A 线程执行到了B线程的join方法时 A就会等待等B线程都执行完 A才会执行

 

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

*/

 

 

class demo implements Runnable

{

         publicvoid run()

         {

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

                   {

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

                   Thread.yield();

                   }

         }

}

 

 

 

class Joindemo

{

         publicstatic void main(String[] args) throws Exception

         {

                   demod=new demo();

                    

                   Threadt1=new Thread(d);

                   Threadt2=new Thread(d);

                  

                   t1.start();

         //      t1.setPriority(Thread.MAX_PRIORITY);

                   t2.start();

                   //t1.join();//

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

                   {

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

                   }

                   System.out.println("over");

         }

}

 

 

/*

对于多个生产者和消费者

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

让被唤醒的线程再一次判断标记

 

为什么定义notifyAll

因为需要唤醒对方线程

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

 

 

*/

 

 

class Resource

{

        

         privateString name;

         privateint count=1;

         privateboolean flag=false;

 

         publicsynchronized void set(String name)

         {

                  

                  

                   while(flag)//if()只判断一次if条件while每次都判断

                   try{this.wait();}catch(Exceptione){}

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

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

                   flag=true;

                  this.notifyAll();//notify();唤醒的是唤醒池中第一个

         }//notifyAll();全部唤醒都去判断标记  唤醒对方线程

         publicsynchronized void out()

         {

                   while(!flag)

                   try{this.wait();}catch(Exceptione){}

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

                   flag=false;

                   this.notifyAll();

         }

}

 

class Producer implements Runnable

{

         privateResource res ;

          Producer(Resource res)

         {

                   this.res=res;

         }

         publicvoid run()

         {

                   while(true)

                   {

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

                   }

                  

         }

}

class Consumer implements Runnable

{

         privateResource res ;

          Consumer(Resource res)

         {

                   this.res=res;

         }

         publicvoid run()

         {

                   while(true)

                   {

                            res.out();

                   }

                  

         }

}

 

 

class Producerdemo

{

         publicstatic void main(String[] args)

         {

                   Resourcer =new Resource();

                   Producerpro=new Producer(r) ;

                   Consumercon=new Consumer(r);

 

                   Threadt1=new Thread(pro);

                   Threadt2=new Thread(pro);

                   Threadt3=new Thread(con);

                   Threadt4=new Thread(con);

 

                  

                   t1.start();

                   t2.start();

                   t3.start();

                   t4.start();

         }

}

 

 

/*

 

 

/*

多线程停止:

stop方法已经过时 如何停止线程

只有一种 run方法结束

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

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

特殊情况:当线程处于冻结状态就不会读取到标记那么线程就不会结束

 

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

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

 

Thread类提供该方法 interrupt():

*/

 

class Stopthread implements Runnable

{

         privateboolean flag=true;

    public synchronized void run()

         {       

          while(flag)

         {

                    try

                    {

                            wait();

                    }

                    catch (InterruptedException e)

                    {

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

                            flag=false;

                    }

        

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

          }

         }

         publicvoid changeFlag()

         {

                   flag=false;

         }

}

 

class Stopdemo

{

         publicstatic void main(String[] args)

         {

                    Stopthread st =new Stopthread();

                    

                   Threadt1=new Thread(st);

                   Threadt2=new Thread(st);

                           

                   t1.start();

                   t2.start();

 

                   intnum=0;

                   while(true)

                   {

                            if(num++==60)

                            {

                            //      st.changeFlag();

                            t1.interrupt();

                            t2.interrupt();

                                     break;

 

                            }

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

                   }

         System.out.println("ocer");

         }

}

 

set.Deamon();

*/

 

 

 

 

class Stopthread implements Runnable

{

         privateboolean flag=true;

    public void run()

         {       

          while(flag)

         {       

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

          }

         }

         publicvoid changeFlag()

         {

                   flag=false;

         }

}

 

class Stopdemo1

{

         publicstatic void main(String[] args)

         {

                    Stopthread st =new Stopthread();

                    

                   Threadt1=new Thread(st);

                   Threadt2=new Thread(st);

                            t1.setDaemon(true);

                            t2.setDaemon(true);

                   t1.start();

                   t2.start();

 

                   intnum=0;

                   while(true)

                   {

                            if(num++==60)

                            {

                  

                                     break;

 

                            }

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

                   }

         System.out.println("ocer");

         }

}

 

 

/*

Thread 写法

 

*/

 

 

class Threadtest

{

         publicstatic void main(String[] args)

         {

                   newThread()//Thread类的子类对象

                   {

                            publicvoid run()

                            {

                                     for(int x=0;x<100 ;X++ )

                                     {

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

        

                                     }

                            }

         }.start();

 

         Runnabler =new Runnable()

                   {

                                     publicvoid run()

                            {

                                     for(int x=0;x<100 ;X++ )

                                     {

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

        

                                     }

                            }

 

         };

         newThread(r).start();

        

         }

}

 

 

 

/*

Thread 写法

 

*/

 

 

class Threadtestdemo

{

         publicstatic void main(String[] args)

         {

                   newThread()//Thread类的子类对象

                   {

                            publicvoid run()

                            {

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

                                     {

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

        

                                     }

                            }

             }.start();

        

         Runnabler =new Runnable()

                   {

                                     publicvoid run()

                            {

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

                                     {

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

        

                                     }

                            }

 

                   };

         newThread(r).start();

        

         }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值