多线程和线程同步

2019-10-15  本文已影响0人  Hsicen

线程和进程

进程和线程
CPU线程和操作系统线程

CPU线程:

操作系统线程:

单核CPU也可以利用时间分片方式运行多线程操作系统

线程是什么

多线程的使用

Thread
Thread thread = new Thread() {
  @Override
  public void run() {
      super.run();  //执行Runnable的run()方法
      System.out.println("Thread start");
  }
   };

thread.start();
Runnable
Thread thread = new Thread(new Runnable() {
  @Override
  public void run() {
      System.out.println("Thread with runnable start");
  }
});

thread.start();
ThreadFactory
ThreadFactory threadFactory = new ThreadFactory() {
  int count = 0;  //线程安全问题
  @Override
  public Thread newThread(Runnable r) {
      count++;
      return new Thread(r, "Thread-" + count);
  }
};

Runnable runnable = new Runnable() {
  @Override
  public void run() {
      System.out.println(Thread.currentThread().getName() + " start");
  }
};

threadFactory.newThread(runnable).start();
threadFactory.newThread(runnable).start();
threadFactory.newThread(runnable).start();
Executor线程池
Runnable runnable = new Runnable() {
  @Override
  public void run() {
      System.out.println(Thread.currentThread().getName());
  }
};

ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(runnable);
executorService.execute(runnable);
executorService.execute(runnable);

executorService.shutdown();
Callable和Future
Callable<String> callable = new Callable<String>() {
  @Override
  public String call() throws Exception {

      try {
          Thread.sleep(1500);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }

      return "Done";
  }
};

ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> future = executorService.submit(callable);

try {
  String result = future.get();
  System.out.println("result = " + result);
} catch (ExecutionException | InterruptedException e) {
  e.printStackTrace();
} finally {
  executorService.shutdown();
}

线程同步与线程安全

synchronized
private synchronized void count(int newValue) {
  x = newValue;
  y = newValue;

  if (x != y) {
      System.out.println("x = " + x + ",      y = " + y);
  }
}
private void count(int newValue) {
  synchronized (this){
      x = newValue;
      y = newValue;
      }

  if (x != y) {
      System.out.println("x = " + x + ",  y = " + y);
  }
}
public static synchronized void count(int newValue) {
  x = newValue;
  y = newValue;

  if (x != y) {
      System.out.println("x = " + x + ",      y = " + y);
  }
}
  • 保证方法内部或代码块内部的资源(数据)的互斥访问。即同一时间,由同一个Monitor监视的代码,最多只能有一个线程在访问
  • 保证线程之间对监视资源的数据同步。即任何线程在获取到Monitor后的第一时间,会先将共享内存中的数据复制到自己的缓存中;任何线程在释放Monitor的第一时间,会先将缓存中的数据复制到共享内存中
volatile
java.util.concurrent.atomic包
AtomicInteger num = new AtomicInteger(0);
......
num.getAndIncrement();
Lock & ReentrantReadWriteLock
Lock lock = new ReentrantLock();
......
lock.lock();
try {
  x++;
} finally{
  //保证在方法在提前结束或出现Exception的时候,依然能正常释放锁
  lock.unlock();
}
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Lock readLock = lock.readLock();
Lock writeLock = lock.writeLock();
private int x = 0;

/*** 写操作加锁 */
private void count(){
  writeLock.lock();
  try {
      x++;
      } finally{
          writeLock.unlock();
      }
}

/*** 读操作加锁 */
private void print (int time) {
  readLock.lock();
  try{
      for (int i = 0; i< time; i++){
          System.out.print(x + " ");
          }
          System.out.println();
      } finally {
          readLock.unlock();
      }
}
线程安全问题的本质

在多个线程访问共同的资源时,在某一个线程对资源进行写操作的途中(写操作已经开始,但是还没有结束),其它线程对这个写入了一半的资源进行了读操作,或者基于这个写了一半的资源进行了写操作,导致出现数据错误

锁机制的本质

通过对共享资源进行访问限制,让同一时间只有一个线程可以访问资源,保证了数据的准确性

不论是线程安全问题,还是针对线程安全问题所衍生出的锁机制,它们的核心都在于共享的资源,而不是某个方法或者某几行代码

上一篇 下一篇

猜你喜欢

热点阅读