Java定时总结(Rx一行代码解决orz)

定时任务

  • Rx
public class RxUtils {

    static public Observable countDown(int time) {
        if (time < 0) time = 0;
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .map(new Func1() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);

//
//        Observable.timer(time,TimeUnit.SECONDS).filter(new Func1() {
//            @Override
//            public Boolean call(Long aLong) {
//                return null;
//            }
//        })
    }
}
  • Timer

      Timer timer = new Timer();
      TimerTask timerTask = new TimerTask() {
          @Override
          public void run() {
              LogUtil.v("java", "任务开始");
          }
      };
      timer.schedule(timerTask, 1000);
      timer.schedule(timerTask, 1000);
    
        ps:timer.cancel;
    
  • Handler

       Handler handler = new Handler();
          Runnable runnable = new Runnable() {
              @Override
              public void run() {
                  LogUtil.v("java", "定时任务开启");
              }
          };
       handler.postDelayed(runnable, 1000);
    
      //handler.removeCallbacksAndMessages(null);
    
  • AlarmManager

         am = (AlarmManager) this.getSystemService(ALARM_SERVICE);
    
      Intent i = new Intent(this, UpdateReceiver.class);
    
      PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);
    
      //am.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pendingIntent);
    
      am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1000, pendingIntent);
    

锁机制

  • 概念
    • 原子性:只有一个线程能够执行这个代码
    • 可见性: 保证前后修改的资源一致
  • 分类
    • synchronized

    • ReentrantLock:可重入的意义在于持有锁的线程可以继续持有,并且要释放对等的次数后才真正释放该锁

      class Outputter1 {    
          private Lock lock = new ReentrantLock();// 锁对象    
      
          public void output(String name) {           
              lock.lock();      // 得到锁    
        
              try {    
                  //do something
              } finally {    
                  lock.unlock();// 释放锁    
              }    
          }    
      }            
      
    • ReadWriteLock:可以同时读取,限制写入

          class Data {        
              private int data;// 共享数据    
              private ReadWriteLock rwl = new ReentrantReadWriteLock();       
              
              public void set(int data) {    
                  rwl.writeLock().lock();// 取到写锁    
                  try {    
                      System.out.println(Thread.currentThread().getName() + "准备写入数据");    
                      try {    
                          Thread.sleep(20);    
                      } catch (InterruptedException e) {    
                          e.printStackTrace();    
                      }    
                      this.data = data;    
                      System.out.println(Thread.currentThread().getName() + "写入" + this.data);    
                  } finally {    
                      rwl.writeLock().unlock();// 释放写锁    
                  }    
              }       
            
              public void get() {    
                  rwl.readLock().lock();// 取到读锁    
                  try {    
                      System.out.println(Thread.currentThread().getName() + "准备读取数据");    
                      try {    
                          Thread.sleep(20);    
                      } catch (InterruptedException e) {    
                          e.printStackTrace();    
                      }    
                      System.out.println(Thread.currentThread().getName() + "读取" + this.data);    
                  } finally {    
                      rwl.readLock().unlock();// 释放读锁    
                  }    
              }    
          }    
      
    • 和Condition的结合

          class BoundedBuffer {  
             final Lock lock = new ReentrantLock();//锁对象  
             final Condition notFull  = lock.newCondition();//写线程条件   
             final Condition notEmpty = lock.newCondition();//读线程条件   
            
             final Object[] items = new Object[100];//缓存队列  
             int putptr/*写索引*/, takeptr/*读索引*/, count/*队列中存在的数据个数*/;  
            
             public void put(Object x) throws InterruptedException {  
               lock.lock();  
               try {  
                 while (count == items.length)//如果队列满了   
                   notFull.await();//阻塞写线程  
                 items[putptr] = x;//赋值   
                 if (++putptr == items.length) putptr = 0;//如果写索引写到队列的最后一个位置了,那么置为0  
                 ++count;//个数++  
                 notEmpty.signal();//唤醒读线程  
               } finally {  
                 lock.unlock();  
               }  
             }  
            
             public Object take() throws InterruptedException {  
               lock.lock();  
               try {  
                 while (count == 0)//如果队列为空  
                   notEmpty.await();//阻塞读线程  
                 Object x = items[takeptr];//取值   
                 if (++takeptr == items.length) takeptr = 0;//如果读索引读到队列的最后一个位置了,那么置为0  
                 --count;//个数--  
                 notFull.signal();//唤醒写线程  
                 return x;  
               } finally {  
                 lock.unlock();  
               }  
             }   
           }          
      

多线程总结

  • 管理类

    • 基本

        ExecutorService e = Executors.newCachedThreadPool();
        ExecutorService e = Executors.newSingleThreadExecutor();
        ExecutorService e = Executors.newFixedThreadPool(3);
        // 第一种是可变大小线程池,按照任务数来分配线程,
        // 第二种是单线程池,相当于FixedThreadPool(1)
        // 第三种是固定大小线程池。
        // 然后运行
        e.execute(new MyRunnableImpl());
      
    • 定时任务线程

        ScheduledExecutorService  threadPools = Executors.newScheduledThreadPool(2);  
          
        for(int i = 0; i < 2;i++){  
            threadPools.schedule(new Runnable() {  
                @Override  
                public void run() {  
                        System.out.println(Thread.currentThread().getName() + "定时器执行");  
                }  
            }, 2, TimeUnit.SECONDS);  
      
            
            
        }  
      
        threadPools.shutdown();  
            
        //scheduleAtFixedRate 这个方法是不管你有没有执行完,反正我每隔4秒来执行一次,以相同的频率来执行
      
        //scheduleWithFixedDelay 这个是等你方法执行完后,我再隔4秒来执行,也就是相对延迟后,以固定的频率去执行
      
  • Semaphore就是一个信号量,它的作用是限制某段代码块的并发数

  • FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现,RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

      public class Test {
          public static void main(String[] args) {
              //第一种方式
              ExecutorService executor = Executors.newCachedThreadPool();
              Task task = new Task();
              FutureTask futureTask = new FutureTask(task);
              executor.submit(futureTask);
              executor.shutdown();
               
              //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
              /*Task task = new Task();
              FutureTask futureTask = new FutureTask(task);
              Thread thread = new Thread(futureTask);
              thread.start();*/
               
              try {
                  Thread.sleep(1000);
              } catch (InterruptedException e1) {
                  e1.printStackTrace();
              }
               
              System.out.println("主线程在执行任务");
               
              try {
                  System.out.println("task运行结果"+futureTask.get());
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } catch (ExecutionException e) {
                  e.printStackTrace();
              }
               
              System.out.println("所有任务执行完毕");
          }
      }
      class Task implements Callable{
          @Override
          public Integer call() throws Exception {
              System.out.println("子线程在进行计算");
              Thread.sleep(3000);
              int sum = 0;
              for(int i=0;i<100;i++)
                  sum += i;
              return sum;
          }
      }
    

参考

  • http://blog.csdn.net/dxpqxb/article/details/8659292
  • http://blog.csdn.net/vking_wang/article/details/9952063
  • http://www.jianshu.com/p/40d4c7aebd66 多线程
  • http://mybar.iteye.com/blog/1829883 线程池
  • http://www.cnblogs.com/dolphin0520/p/3949310.html Future
  • http://blog.csdn.net/yaojiank/article/details/8888186

你可能感兴趣的:(Java定时总结(Rx一行代码解决orz))