线程基础

作者: Czw_hacker | 来源:发表于2016-10-18 16:55 被阅读36次

** java中创建线程的方法**

  • 继承自java.lang.thread类,并重写run方法(线程运行时要做的事)
  • 实现java.lang.Runnable接口,并实现run方法
public class MyThread extends Thread {

    @Override
    public void run() {
    //线程里应该执行的程序
        }
    }
public class MyThread1 implements Runnable {

    @Override
    public void run() {
    //子线程执行的代码
    }
}

** 线程启动**

  • 当线程是通过继承自Thread类来实现的,那么就可以通过父类的start()方法来启动线程,线程结束后JVM会调用线程类中的run()方法。
    public static void main(String[] args) {
        
        MyThread mt = new MyThread();
        mt.start();
        }
  • 当线程类是通过实现Runnable接口来实现的,必须通过Thread类来启动
    public static void main(String[] args) {
        
        MyThread1 mt1 = new MyThread1();
        Thread th = new Thread(mt1);
        th.start();
    }

** 线程生命周期**

  • 调用Thread类的静态方法sleep()可以让线程进入休眠,线程休眠后将会进入就绪状态
  • 线程一旦死亡不能再次使用(调用start())

线程的分类

  • join线程和守护线程
  • 守护线程会随着主线程死亡而死亡不管是否结束
  • join线程工作时像插队做事,一旦插入程序开始工作就一直到执行完毕不会进入阻塞状态。
    public static void main(String[] args) {
        
        MyThread mt = new MyThread();
        mt.setDaemon(true);//标记为守护线程
        mt.start();//
    }

线程同步(线程安全)

  • 产生线程不安全的条件

    1.在多线程情况下
    2.同一个对象
    3.实例变量(属性)
    
  • 解决线程安全

    1.给线程加锁(使用synchronized关键字)
    2.同步代码块
    3.使用reentrantLock类
    
给线程加锁,只能用在方法的声明上,很多时候并不需要整个方法中的代码全部加锁
    public synchronized void  pickmoney(String name ,int money){
        
                if(this.money > money){
                this.money = this.money - money;
                System.out.println(name+"取款成功"+this.money);
            }else{
                System.out.println("余额不足");
            }
同步代码块
        synchronized (this){
            if(this.money > money){
                this.money = this.money - money;
                System.out.println(name+"取款成功"+this.money);
            }else{
                System.out.println("余额不足");
            }
        }
使用reentrantLock方法
    //创建reentrantLock对象
    ReentrantLock reen = new ReentrantLock();
    
    public void  pickmoney(String name ,int money){
        try{
            //调用方法lock 上锁
            reen.lock();
            if(this.money > money){
            this.money = this.money - money;
            System.out.println(name+"取款成功"+this.money);
        }else{
            System.out.println("余额不足");
        }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            //调用方法unlock解锁
            reen.unlock();
        }ection

** 线程安全集合**

  • 可以通过Collections中的synchronized XXX() 来使用线程安全的集合

  • List<String> list = Collections.synchronizedList(new ArrayList<String>());

  • Set<String> set = Collections.synchronizedSet(new HashSet<String>());

  • Map<String,String> map = Collections.synchronizedMap(new HashMap<String, String>());

相关文章

网友评论

    本文标题:线程基础

    本文链接:https://www.haomeiwen.com/subject/cgdtuttx.html