浅谈Java多线程

Java中多线程涉及下面4点

  1. 创建单线程:继承Tread类 和 实现Rannable接口;
  2. 多线程使用:手动实例化多个线程 或者 使用线程池 ExecutorService;
  3. 多线程共享数据同步:可以采用同步synchronized执行run方法中的操作;
  4. 合理使用多线程同步数据,防止死锁问题。


1.创建线程

  1. 继承Tread类
    public class MyThread extends Thread {
        
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
        
        public static void main(String[] args) {
            //不能共享数据
            //MyThread myThread = new MyThread(); 
            //能共享数据
            Thread myThread = new Thread(new MyThread());
            myThread.start(); 
        }
    }
  2. 实现Rannable接口

    public class MyThread implements Runnable {
        
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
        
        public static void main(String[] args) {
            //能共享数据
            Thread  myThread = new Thread(new MyThread());   
            myThread.start();
        }
    }
    上面写了两种创建线程的例子,注意:注释内容。

2.多线程使用

  1. 手动实例化自定义的线程类
    public class MyThread implements Runnable {
        
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
        
        public static void main(String[] args) {
            MyThread myThread  = new MyThread();
            new Thread(myThread).start();
            new Thread(myThread).start();
            new Thread(myThread).start();
        }
    }
  2. 使用线程池 ExecutorService

    public class MyThread implements Runnable {
        
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
        
        public static void main(String[] args) {
            ExecutorService pool = Executors.newCachedThreadPool();
            MyThread myThread = new MyThread();
            for(int i = 0; i < 3; i++){
                pool.execute(myThread);
            }
            //关闭线程池
            pool.shutdown();
        }
    }

3.多线程共享数据同步

一个简单卖票代码:3个卖票员,共卖100张门票,买一张票耗时100毫秒。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThread implements Runnable {

	private int tickets = 100;

	private synchronized void sale() {
		if (tickets > 0) {
			System.out.println(Thread.currentThread().getName() + " 剩余:"
					+ (--tickets) + "张票");
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else{
			Thread.currentThread().stop();
		}
	}

	public void run() {
		while(true){
			sale();			
		}
	}

	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		MyThread myThread = new MyThread();
		for (int i = 0; i < 3; i++) {
			pool.execute(myThread);
		}
		pool.shutdown();
	}

}




4.死锁

当线程之间互相等待共享资源时,会产生死锁问题。我们可以在多线程的程序中减少同步关键字的使用,减少每一次占用资源的时间之类的措施来降低死锁出现的可能性。




你可能感兴趣的:(浅谈Java多线程)