java线程

提到线程不得不提的是进程,进程是操作系统管理运行程序的一种手段,由于进程过于重量级,一个程序想要并行执行,需要开多个进程很不方便,因此提出了线程。线程可以看做是进程的子程序,实际的执行单元。
Java程序是在虚拟机上运行,因此它的线程是由操作系统实现,Jvm提供接口。

线程的定义方式

  1. 继承Thread类

    public class NewThread extends Thread {
        public void run() {
        }
    }   
    
  2. 实现Runnable接口

    public class NewRunnable implements Runnable {
        public void run() {
        }
    }
    

线程的运行时状态

这里写图片描述
这张图展示了线程的整个生命周期,首先是刚创建的线程进入创建状态,start()后进入就绪状态,等待cpu调度,获得cpu调度后进入运行状态,可以调用sleep()或者wait()进入阻塞状态,调用stop()进入死亡状态。
sleep与wait的区别:
- sleep阻塞一段时间后,自动进入就绪状态,不释放对象锁
- wait不会自动进入就绪状态,会释放对象锁

线程的同步

例子1:模拟卖票

public class Demo {

    public static void main(String[] args) {
        Ticket t = new Ticket();
       new Thread(t).start();
       new Thread(t).start();
    }
}

class Ticket implements Runnable {

    int ticket = 100;

    public void run() {      //可以加synchronized关键字,解决同步问题
        while(ticket > 0) {
            System.out.println(Thread.currentThread().getName() +           "卖出了第" + ticket + "张票");
            --ticket;
        }
    }
}

这里写图片描述
这里可以看出100出现了两次,因此我们必须让数据同步,可以在需要同步的方法前加 synchronized实现,保证线程执行的原子性


例子2:生产者与消费者,生产一个消费一个

public class Demo {

    public static void main(String[] args) {
        Resource res = new Resource();
        new Thread(new Production(res)).start();
        new Thread(new Production(res)).start();
        new Thread(new Custom(res)).start();
        new Thread(new Custom(res)).start();
    }
}

class Resource {
    int count = 0;
    boolean flag = false;

    synchronized public  void set() {
        while(flag == true) {
            try{this.wait();}catch(Exception e){}
        }
        count++;
        System.out.println(Thread.currentThread().getName() + "生产了" +count + "个");
        flag = true;    
        notifyAll();
    }

    synchronized public void get() {
        while(flag == false) {
            try{this.wait();}catch(Exception e){}
        }
        System.out.println(Thread.currentThread().getName() + "----------消费了" 
                                +count + "个");
        flag = false;
        notifyAll();
    }
}

class Production implements Runnable{
    Resource res;
    public Production(Resource res) {
        this.res = res;
    }

    public void run() {
        while(true) {
            res.set();
        }
    }
}

class Custom implements Runnable{
    Resource res;
    public Custom(Resource res) {
            this.res = res;
    }

    public void run() {
        while(true) {
            res.get();
        }
    }

}

线程锁机制

  1. 同步代码块
  2. 同步函数的锁为this对象
  3. 静态同步函数的锁为class对象
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值