浅谈Java多线程
Java中多线程涉及下面4点
- 创建单线程:继承Tread类 和 实现Rannable接口;
- 多线程使用:手动实例化多个线程 或者 使用线程池 ExecutorService;
- 多线程共享数据同步:可以采用同步synchronized执行run方法中的操作;
- 合理使用多线程同步数据,防止死锁问题。
1.创建线程
- 继承Tread类
1 public class MyThread extends Thread { 2 3 public void run() { 4 System.out.println(Thread.currentThread().getName()); 5 } 6 7 public static void main(String[] args) { 8 //不能共享数据 9 //MyThread myThread = new MyThread(); 10 //能共享数据 11 Thread myThread = new Thread(new MyThread()); 12 myThread.start(); 13 } 14 }
- 实现Rannable接口
1 public class MyThread implements Runnable { 2 3 public void run() { 4 System.out.println(Thread.currentThread().getName()); 5 } 6 7 public static void main(String[] args) { 8 //能共享数据 9 Thread myThread = new Thread(new MyThread()); 10 myThread.start(); 11 } 12 }
上面写了两种创建线程的例子,注意:注释内容。
2.多线程使用
- 手动实例化自定义的线程类
1 public class MyThread implements Runnable { 2 3 public void run() { 4 System.out.println(Thread.currentThread().getName()); 5 } 6 7 public static void main(String[] args) { 8 MyThread myThread = new MyThread(); 9 new Thread(myThread).start(); 10 new Thread(myThread).start(); 11 new Thread(myThread).start(); 12 } 13 }
- 使用线程池 ExecutorService
1 public class MyThread implements Runnable { 2 3 public void run() { 4 System.out.println(Thread.currentThread().getName()); 5 } 6 7 public static void main(String[] args) { 8 ExecutorService pool = Executors.newCachedThreadPool(); 9 MyThread myThread = new MyThread(); 10 for(int i = 0; i < 3; i++){ 11 pool.execute(myThread); 12 } 13 //关闭线程池 14 pool.shutdown(); 15 } 16 }
3.多线程共享数据同步
一个简单卖票代码:3个卖票员,共卖100张门票,买一张票耗时100毫秒。
1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 4 public class MyThread implements Runnable { 5 6 private int tickets = 100; 7 8 private synchronized void sale() { 9 if (tickets > 0) { 10 System.out.println(Thread.currentThread().getName() + " 剩余:" 11 + (--tickets) + "张票"); 12 try { 13 Thread.sleep(100); 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 } else{ 18 Thread.currentThread().stop(); 19 } 20 } 21 22 public void run() { 23 while(true){ 24 sale(); 25 } 26 } 27 28 public static void main(String[] args) { 29 ExecutorService pool = Executors.newCachedThreadPool(); 30 MyThread myThread = new MyThread(); 31 for (int i = 0; i < 3; i++) { 32 pool.execute(myThread); 33 } 34 pool.shutdown(); 35 } 36 37 }
4.死锁
当线程之间互相等待共享资源时,会产生死锁问题。我们可以在多线程的程序中减少同步关键字的使用,减少每一次占用资源的时间之类的措施来降低死锁出现的可能性。