JAVA线程编程

来源:互联网 发布:java从文件中读取一行 编辑:程序博客网 时间:2024/06/05 19:03
原文地址:JAVA线程编程作者:illool

//多线程和单线程
class threaddemo1
{
 public static void main(String [] args)
  
   newtestthread().start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   while(true)
   {
     System.out.println("main:"+Thread.currentThread().getName());
   }
 
}

class testthread extendsThread   //创建Thread子类,重写run()方法;
{
  public void run()
  {
    while(true)
    {
      System.out.println("run:"+Thread.currentThread().getName());
    }
  }
}



 

 

 

//后台线程
class threaddemo11
{
 public static void main(String [] args)
  
   Thread tt =new testthread();
   tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
 
}

class testthread extendsThread   //创建Thread子类,重写run()方法;
{
  public void run()
  {
    while(true)
    {
      System.out.println("run:"+Thread.currentThread().getName());
    }
  }
}

 

 

//join()方法
class threaddemo12
{
 public static void main(String [] args)
  
   Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   int index =0;
   while(true)
   {
     if(index++== 100)
          try{tt.join(10000);}catch(Exceptione){}//循环100次以后,子类tt中的线程合并到住线程中去
     System.out.println("main:"+Thread.currentThread().getName());
   }
 
}

class testthread extendsThread   //创建Thread子类,重写run()方法;
{
  public void run()
  {
    while(true)
    {
      System.out.println("run:"+Thread.currentThread().getName());
    }
  }
}

 

 

 

//不使用Runnable 的接口对象的创建,但创建4个独立的线程
class threaddemo13
{
 public static void main(String [] args)
  
   //Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   //Thread tt =new Thread(newtestthread());//创建一个线程对象,并传入一个Runnable的线程对象;将不在自动的调用Thread
                       //类中自带的run()方法了,而调用Runnable对象中的run()方法; 
   //tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
   newtestthread().start();//产生4个线程
   newtestthread().start();
   newtestthread().start();
   newtestthread().start();
 
}

class testthread extends Thread //用直接继承Thread的方式
                  //创建一个Runnable的接口类的对象 
                  //创建Thread子类,重写run()方法;
{
  int tickets = 100;
  public void run()
  {
    while(true)
    {
     if(tickets>0)
      System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
    }
  }
}

 

 

//不使用Runnable 的接口对象的创建,在同一个线程对象中创建4个线程
class threaddemo14
{
 public static void main(String [] args)
  
   //Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   //Thread tt =new Thread(newtestthread());//创建一个线程对象,并传入一个Runnable的线程对象;将不在自动的调用Thread
                       //类中自带的run()方法了,而调用Runnable对象中的run()方法; 
   //tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
   testthread tt= new testthread();//产生一个对象,并启动4个线程,实现拥有共同的tickets=100
   tt.start();           //实际只有一个线程在工作
   tt.start();
   tt.start();
   tt.start();
 
}

class testthread extendsThread//创建一个Runnable的接口类的对象   
                  //创建Thread子类,重写run()方法;
{
  int tickets = 100;
  public void run()
  {
    while(true)
    {
      if(tickets>0)
      System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
    }
  }
}

 

 

//Runnable 的接口对象的创建
class threaddemo15
{
 public static void main(String [] args)
  
   //Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   //Thread tt =new Thread(newtestthread());//创建一个线程对象,并传入一个Runnable的线程对象;将不在自动的调用Thread
                       //类中自带的run()方法了,而调用Runnable对象中的run()方法; 
   //tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
   testthread tt= new testthread();//产生一个对象,这个对象是以Runnable实现的
   
   newThread(tt).start();   //再将Runnable的对象传到Thread里去;
   newThread(tt).start();
   newThread(tt).start();
   newThread(tt).start();
 
}

class testthread implements Runnable//extendsThread//创建一个Runnable的接口类的对象   
                  //创建Thread子类,重写run()方法;
{
  int tickets = 100;
  public void run()
  {
    while(true)
    {
      if(tickets>0)
      System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
    }
  }
}

 

 

//多线程的安全,防止资源被同时的使用:synchronized(str),是以牺牲程序上午性能为代价的
class threaddemo16
{
 public static void main(String [] args)
  
   //Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   //Thread tt =new Thread(newtestthread());//创建一个线程对象,并传入一个Runnable的线程对象;将不在自动的调用Thread
                       //类中自带的run()方法了,而调用Runnable对象中的run()方法; 
   //tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
   testthread tt= new testthread();//产生一个对象,这个对象是以Runnable实现的
   
   newThread(tt).start();   //再将Runnable的对象传到Thread里去;
   newThread(tt).start();
   newThread(tt).start();
   newThread(tt).start();
 
}

class testthread implements Runnable//extendsThread//创建一个Runnable的接口类的对象   
                  //创建Thread子类,重写run()方法;
{
  int tickets = 100;
  String str = new String("");  //必须定义在run()方法的外面;如定义在里面,4个线程就会创建4个str对象;
  public void run()
  {
    while(true)
    {
      synchronized(str) //synchronized(str)的括号中必须是一个对象,可以任意的定义一个对象,实现了同步;
                //检查str的标志位;叫同步代码块
      {
          if(tickets>0)
          {
            try{Thread.sleep(10);}catch(Exceptione){};//让线程暂停10mm,最终出现异常。
            System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
            //在一个线程在执行完tickets>0以后,其他的线程不可以执行if里面的代码;
          }
      }
    }
  }
}

 

 

 

//多线程的安全,防止资源被同时的使用:synchronized(str),是以牺牲程序上午性能为代价的
//使用同步函数实现同步;
class threaddemo17
{
 public static void main(String [] args)
  
   //Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   //Thread tt =new Thread(newtestthread());//创建一个线程对象,并传入一个Runnable的线程对象;将不在自动的调用Thread
                       //类中自带的run()方法了,而调用Runnable对象中的run()方法; 
   //tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
   testthread tt= new testthread();//产生一个对象,这个对象是以Runnable实现的
   
   newThread(tt).start();   //再将Runnable的对象传到Thread里去;
   try{Thread.sleep(1);}catch(Exceptione){}  //让CPU暂停,则又开始了上一条语句所指示的线程开始执行;
   tt.str = newString("method");
   newThread(tt).start();
   newThread(tt).start();
   tt.str = newString("method");
   newThread(tt).start();
 
}

class testthread implements Runnable//extendsThread//创建一个Runnable的接口类的对象   
                  //创建Thread子类,重写run()方法;
{
  int tickets = 100;
  String str = new String("");  //必须定义在run()方法的外面;如定义在里面,4个线程就会创建4个str对象;
  public void run()
  {
    if(str.equals("method"))
    {
        while(true)
        {
          synchronized(str) //synchronized(str)的括号中必须是一个对象,可以任意的定义一个对象,实现了同步;
                    //检查str的标志位;叫同步代码块
          {
              if(tickets>0)
              {
                try{Thread.sleep(10);}catch(Exceptione){};//让线程暂停10mm,最终出现异常。
                System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
                //在一个线程在执行完tickets>0以后,其他的线程不可以执行if里面的代码;
              }
          }
        }
    }
    else
    {
       while(true)
       {
         sale();
       }
    }
  }
  public synchronized voidsale()    //使用的是this来作为监视对象的
  {
       if(tickets>0)
          {
            try{Thread.sleep(10);}catch(Exceptione){};//让线程暂停10mm,最终出现异常。
            System.out.println("this");
            System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
            //在一个线程在执行完tickets>0以后,其他的线程不可以执行if里面的代码;
          }
  }
}

//由于使用的是不同的两个对象的标志位,来作为监视的对象,所以同步代码和同步函数之间就不可能出现同步;

 

 

 

//死锁问题,对str 和 this 两个对象的标志为的监视,所出现的问题;
class threaddemo18
{
 public static void main(String [] args)
  
   //Thread tt =new testthread();
   //tt.setDaemon(true); //setDaemon(true)方法,这个线程就变成了后台线程
   //Thread tt =new Thread(newtestthread());//创建一个线程对象,并传入一个Runnable的线程对象;将不在自动的调用Thread
                       //类中自带的run()方法了,而调用Runnable对象中的run()方法; 
   //tt.start();//run();
   //start()方法启动后会调用run()方法,run()是个空的函数;
   
   testthread tt= new testthread();//产生一个对象,这个对象是以Runnable实现的
   
   newThread(tt).start();   //再将Runnable的对象传到Thread里去;
   try{Thread.sleep(1);}catch(Exceptione){}  //让CPU暂停,则又开始了上一条语句所指示的线程开始执行;
   tt.str = newString("method");
   newThread(tt).start();
   newThread(tt).start();
   tt.str = newString("method");
   newThread(tt).start();
 
}

class testthread implements Runnable//extendsThread//创建一个Runnable的接口类的对象   
                  //创建Thread子类,重写run()方法;
{
  int tickets = 100;
  String str = new String("");  //必须定义在run()方法的外面;如定义在里面,4个线程就会创建4个str对象;
  public void run()
  {
    if(str.equals("method"))
    {
        while(true)
        {
          synchronized(str) //synchronized(str)的括号中必须是一个对象,可以任意的定义一个对象,实现了同步;
                    //检查str的标志位;叫同步代码块
          {
              if(tickets>0)
              {
                try{Thread.sleep(10);}catch(Exceptione){};//让线程暂停10mm,最终出现异常。
                synchronized(this){}  //等待this的标志位的释放;死锁出现的点;
                System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
                //在一个线程在执行完tickets>0以后,其他的线程不可以执行if里面的代码;
              }
          }
        }
    }
    else
    {
       while(true)
       {
         sale();
       }
    }
  }
  public synchronized voidsale()    //使用的是this来作为监视对象的
  {
       if(tickets>0)
          {
            try{Thread.sleep(10);}catch(Exceptione){};//让线程暂停10mm,最终出现异常。
            synchronized(str){}  //等待str的标志位的释放;死锁出现的点;
            System.out.println("this");
            System.out.println("run:"+Thread.currentThread().getName()+ "出售的票号码:" + tickets--);
            //在一个线程在执行完tickets>0以后,其他的线程不可以执行if里面的代码;
          }
  }
}

 

 

 

//线程之间的通信
class producer implements Runnable //重复的放入数据
{
  Q q;
  public producer(Q q)
  {
    this.q=q;
  }
  public void run()
  {
    inti=0;
    while(true)
     
      
      synchronized(q)//如没有synchronized(this),就不能实现同步,在刚存如名字的时候,线程就切换到了取的线程
      {
       if(q.bFULL==true)
         //try{wait();}catch(Exceptione){}  //让出线程;
         try{q.wait();}catch(Exceptione){} //让出线程;在调用wait()是必须和synchronized(q)指定的监视器相同
       if(i==0)
       {
       q.name="gao";
       try{Thread.sleep(1);}catch(Exceptione){}  //模拟线程的中断
       q.sex="m";
       }
       else
       {
       q.name="cai";
       q.sex="f";
       }
       i = (i+1)%2; //交替i的值,不是0,就是1;放在那里都一样!
       q.bFULL=true;//标志位置位
       //notify(); //通知数据上传完毕;必须放在同步代码里面;
       q.notify(); //通知数据上传完毕;在调用notify是必须和synchronized(q)指定的监视器相同
      
     //i= (i+1)%2; //交替i的值,不是0,就是1;
    }
  }
}
class consumer implements Runnable //不停的取出数据,并打印出来
{
  Q q;
  public consumer(Q q)
  {
    this.q=q;
  }
  public void run()
  {
    while(true)
    {
     synchronized(q)//如没有synchronized(this),就不能实现同步,在刚存如名字的时候,线程就切换到了取的线程
     {
      if(q.bFULL==false)
         //try{wait();}catch(Exceptione){}  //让出线程;
         try{q.wait();}catch(Exceptione){} //让出线程;在调用wait()是必须和synchronized(q)指定的监视器相同,负责运行会出错
      System.out.println(q.name);
      System.out.println(q.sex);
      q.bFULL=false; //标志位置位
      //notify(); //通知数据上传完毕
      q.notify(); //通知数据上传完毕;在调用notify是必须和synchronized(q)指定的监视器相同
     }
    }
  }
}
class Q  //模拟缓冲区
{
   String name ="unknow";
   String sex ="unknow";
   boolean bFULL= false;
}

class threadcommunication
{
  public static void main (String[] args)
  {
    Qq = new Q();
    newThread(new producer(q)).start();//先新建一个线程,再将生产者和消费者的方法传如线程,然后启动start;
    newThread(new consumer(q)).start();
  }
}

//wait()告诉当前线程放弃监视器并进入睡眠状态直到其他线程进入同一监视器并调用notify为止;
//notify()唤醒同一对象监视器中调用wiat的第一个线程。
//notify All:唤醒同一对象监视器中调用wait的所有线程,具有最高优先级的线程首先被唤醒并执行。
//前提是同一监视器;

 

 

 

//线程之间的通信
class producer implements Runnable //重复的放入数据
{
  Q q;
  public producer(Q q)
  {
    this.q=q;
  }
  public void run()
  {
    inti=0;
    while(true)
     
      
      synchronized(q)//如没有synchronized(this),就不能实现同步,在刚存如名字的时候,线程就切换到了取的线程
      {
       if(q.bFULL==true)
         //try{wait();}catch(Exceptione){}  //让出线程;
         try{q.wait();}catch(Exceptione){} //让出线程;在调用wait()是必须和synchronized(q)指定的监视器相同
       if(i==0)
       {
       q.name="gao";
       try{Thread.sleep(1);}catch(Exceptione){}  //模拟线程的中断
       q.sex="m";
       }
       else
       {
       q.name="cai";
       q.sex="f";
       }
       i = (i+1)%2; //交替i的值,不是0,就是1;放在那里都一样!
       q.bFULL=true;//标志位置位
       //notify(); //通知数据上传完毕;必须放在同步代码里面;
       q.notify(); //通知数据上传完毕;在调用notify是必须和synchronized(q)指定的监视器相同
      
     //i= (i+1)%2; //交替i的值,不是0,就是1;
    }
  }
}
class consumer implements Runnable //不停的取出数据,并打印出来
{
  Q q;
  public consumer(Q q)
  {
    this.q=q;
  }
  public void run()
  {
    while(true)
    {
     synchronized(q)//如没有synchronized(this),就不能实现同步,在刚存如名字的时候,线程就切换到了取的线程
     {
      if(q.bFULL==false)
         //try{wait();}catch(Exceptione){}  //让出线程;
         try{q.wait();}catch(Exceptione){} //让出线程;在调用wait()是必须和synchronized(q)指定的监视器相同,负责运行会出错
      System.out.println(q.name);
      System.out.println(q.sex);
      q.bFULL=false; //标志位置位
      //notify(); //通知数据上传完毕
      q.notify(); //通知数据上传完毕;在调用notify是必须和synchronized(q)指定的监视器相同
     }
    }
  }
}
class Q  //模拟缓冲区
{
   String name ="unknow";
   String sex ="unknow";
   boolean bFULL= false;
}

class threadcommunication
{
  public static void main (String[] args)
  {
    //Qq = new Q();
    //newThread(new producer(q)).start();//先新建一个线程,再将生产者和消费者的方法传如线程,然后启动start;
    //newThread(new consumer(q)).start();
    threadtestt = new threadtest();
    newThread(t).start();
    for(inti=0;i<100;i++)
    {
      if(i==50)
       t.stopme();
      System.out.println("mainis runing");
    }
  }
}

//wait()告诉当前线程放弃监视器并进入睡眠状态直到其他线程进入同一监视器并调用notify为止;
//notify()唤醒同一对象监视器中调用wiat的第一个线程。
//notify All:唤醒同一对象监视器中调用wait的所有线程,具有最高优先级的线程首先被唤醒并执行。
//前提是同一监视器;
class threadtest implements Runnable
{
  private booleanbStop=false;
  public void stopme()
  {
    bStop=true;
  }
  public void run()
  {
    while(!bStop)
    {
       System.out.println(Thread.currentThread().getName()+ "is runing");
    }
  }


}