Java中线程的介绍和使用

来源:互联网 发布:台达人机界面编程软件 编辑:程序博客网 时间:2024/06/05 16:12

 

一。打开桌面的一个应用程序
     Desktop.getDesktop().open(new File("C:/Users/Administrator/Desktop/面试题.txt"));
 Desktop.getDesktop().open(new File("C:/Users/Administrator/Desktop/腾讯QQ.lnk"));  //开启应用程序
 Desktop.getDesktop().browse(new URI("http://www.baidu.com"));                     //打开一个网页


二.创建线程的两种方法
    1.继承自Thread类,重写run()方法
           public class MyThread extends Thread {

              MyThread(boolean isPos){
  
              }       
         public void run() {

              }
           }
    2.实现Runnable接口,实现run()方法
          public class TestThreadByRunable implements Runnable{

     @Override
     public void run() {
   while(true){
   System.out.println(Thread.currentThread().getName());
   }
      }
            }
           在构造时一般采用:    Thread th = new Thread(new TestThreadByRunable(),"thread3");
                                  th.start();
 
************************************************************************************************                         

三。下面是应用的例子    (使用到了同步方法)
     class Test
{
 public static void main(String[] args)
 {
  Queue q=new Queue();
  Producer p=new Producer(q);
  Consumer c=new Consumer(q);
  p.start();
  c.start();
 }
}
*****************************************************
class Producer extends Thread      //生产者
{
 Queue q;
 Producer(Queue q)
 {
  this.q=q;
 }
 public void run()
 {
  for(int i=0;i<10;i++)             //生产数据
  {
   q.put(i);      
   System.out.println("Producer put "+i);
  }
 }
}
*****************************************************
class Consumer extends Thread    //顾客
{
 Queue q;
 Consumer(Queue q)
 {
  this.q=q;
 }
 public void run()
 {
  while(true)                       //取走数据
  {
   System.out.println("Consumer get "+q.get());
  }
 }
}
*****************************************************
class Queue                   //商场提供方法
{
 int value;
 boolean bFull=false;
 public synchronized void put(int i)    //同步方法
 {
  if(!bFull)                     //如果为假
  {
   value=i;               //产生数据
   bFull=true;
   notify();              //唤醒等待线程(即后面线程可以开始取走数据)
  }
  try
  {
   wait();               //自己进入等待状态
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
   
 }
 public synchronized int get()       //同步方法
 {
  if(!bFull)                       //如果为false,则继续等待
  {
   try
   {
    wait();
   }
   catch(Exception e)
   {
    e.printStackTrace();
   }
  }
  bFull=false;            //如果为真,设置变量bFull为false
  notify();               //唤醒等待线程(即后面线程可以开始继续生产数据)
  return value;
 }
}

************************************************************************************************
四。另外也可以使用同步语句块的方式实现同步
                               //以传入的obj对象作为同步依据
           进入这个方法块就会锁住相应的对象,即obj,直到释放后其他线程才能进入
        
     synchronized(obj){
 
     }

 

    class TicketsSystem
{
 public static void main(String[] args)
 {
  SellThread st=new SellThread();
  
  new Thread(st).start();
  new Thread(st).start();
  new Thread(st).start();
  new Thread(st).start();
 }
}

class SellThread implements Runnable
{
 int tickets=100;
 Object obj=new Object();

 public void run()
 {
    while(true)
     synchronized(obj)     //同步语句块  (在JAVA中,每一个对象都会有一个监视器)
                   {                         //  synchronized(Class.forName("SellThread")) 可以得到当前对象的监视块
                       if(tickets>0)         //实用于静态方法同步
                      try
   {
     Thread.sleep(10);
   }
        catch(Exception e)
   {
     e.printStackTrace();
   } 
   System.out.println("obj:"+Thread.currentThread().getName()+
    " sell tickets:"+tickets);
   tickets--;     
                   } 
 } 
}


************************************************************************************************
五。线程异常处理可以实现下面这两个方法  例如在catch 执行异常时
     先实现这个方法    Thread.setDefaultUncaughtExceptionHandler(new java.lang.Thread.UncaughtExceptionHandler() {
   @Override
   public void uncaughtException(Thread t, Throwable e) {
    
   }
  });

    //否则使用下面这个方法
             th1.setUncaughtExceptionHandler(new java.lang.Thread.UncaughtExceptionHandler() {
   @Override
   public void uncaughtException(Thread t, Throwable e) {
    
   }
  });


   
************************************************************************************************
六。终止运行线程的方法    
     变量控制  并配合  interrupt() 方法

    class TestThread
{
 public static void main(String[] args)
 {
  Thread1 t1=new Thread1();
  t1.start();
  int index=0;
  while(true)
  {
   if(index++==500)
   {
    t1.stopThread();   //终止运行线程
    t1.interrupt();    //如果线程已经抢到时间片,但是不会再运行时,这个方法
    break;           //可以继续终止当前线程,
   }
   System.out.println(Thread.currentThread().getName());
  }
  System.out.println("main() exit");
 }
}

class Thread1 extends Thread
{
 private boolean bStop=false;
 public synchronized void run()
 {
  while(!bStop)
  {
   try
   {
    wait();
   }
   catch(InterruptedException e)
   {
    //e.printStackTrace();
    if(bStop)              //如果变量为真,则应该返回,并停止线程
     return;
   }
   System.out.println(getName());
  }
 }
 public void stopThread()
 {
  bStop=true;
 }
}

************************************************************************************************
七。线程池的使用:
                 ExecutorService threadPool = Executors.newFixedThreadPool(5);
     threadPool.submit(new Runnable(1));
                          threadPool.submit(new Runnable(2));

                threadPool.shutdown();                                   //线程池内现成运行完后执行死亡
                threadPool.shutdownNow();

************************************************************************************************
八。 线程锁的应用

           Lock lock = new ReentrantLock();       //创建一个锁
  public void output(String name){
   int len = name.length();
   lock.lock();                    //锁住的代码块
   try{
    for(int i=0;i<len;i++){
     System.out.print(name.charAt(i));
    }
    System.out.println();
   }finally{
    lock.unlock();               //这里必须释放
   }
  }

********************

           ReadWriteLock rwl = new ReentrantReadWriteLock();     //读写锁
            rwl.readLock().lock();
                        rwl.writeLock().lock();
                
  try {
   
  } catch (InterruptedException e) {
   e.printStackTrace();
  }finally{
   rwl.readLock().unlock();
  }

             
            ArrayBlockingQueue类    (同步集合类,使用时查JDK)
      
      
************************************************************************************************