java 线程

线程集锦

线程的几种的方式 继承Thread 类 ,实现Runable接口
Thread:

    1.  多个线程数据共享,因为Thread也实现Runnable接口
    2. java 单继承,不易扩展
    3. 以卖票实例

  public class TicketThread extends Thread{
    private int ticket = 10;
    public void run(){
        for(int i =0;i<10;i++){
            synchronized (this){
                if(this.ticket>0){
                    try {
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] arg){
        TicketThread t1 = new TicketThread();
        new Thread(t1,"线程1").start();
        new Thread(t1,"线程2").start();
        //也达到了资源共享的目的,此处网上有各种写法,很多写法都是自圆其说,举一些特殊例子来印证自己的观点,然而事实却不尽如此。
    }
}
Runnable:

    1. 可以继承多个类和是实现多个接口
    2. 多个线程数据共享
    3. 以卖票实例

  public class TicketThread extends Thread{
    private int ticket = 10;
    public void run(){
        for(int i =0;i<10;i++){
            synchronized (this){
                if(this.ticket>0){
                    try {
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] arg){
        TicketThread t1 = new TicketThread();
        new Thread(t1,"线程1").start();
        new Thread(t1,"线程2").start();
        //也达到了资源共享的目的,此处网上有各种写法,很多写法都是自圆其说,举一些特殊例子来印证自己的观点,然而事实却不尽如此。
    }
}
线程分--》 用户线程守护线程

 用户线程即运行在前台的线程,而守护线程是运行在后台的线程。 守护线程作用是为其他前台线程的运行提供便利服务,而且仅在普通、非守护线程仍然运行时才需要,比如垃圾回收线程就是一个守护线程。当VM检测仅剩一个守护线程,而用户线程都已经退出运行时,VM就会退出,因为没有如果没有了被守护这,也就没有继续运行程序的必要了。如果有非守护线程仍然存活,VM就不会退出。
守护线程并非只有虚拟机内部提供,用户在编写程序时也可以自己设置守护线程。用户可以用Thread的setDaemon(true)方法设置当前线程为守护线程。

另外有几点需要注意:
1.setDaemon(true)必须在调用线程的start()方法之前设置,否则会跑出IllegalThreadStateException异常。
2.在守护线程中产生的新线程也是守护线程。      
3. 不要认为所有的应用都可以分配给守护线程来进行服务,比如读写操作或者计算逻辑。
线程状态图
线程的生命周期.jpg
线程间的通信 :
  • join 可以指定线程运行的顺序,线程的方法
  • sleep线程休眠,当并不释放锁,线程的方法
  • yield
  • [wait()-->释放对象锁 ,notify()-->随机唤醒一个等待对象的锁,notifyall()--->唤醒所有等待锁得对象,都是对象的方法,并且需要在同步代码块中使用synchronized {}]
  • 消费者与生产者模式
package com.threadPa;

import java.util.LinkedList;
import java.util.Random;

/**
 * Created by bright on 2019/7/15.
 */
public class PC {
    private static final int BUFF_SIZE = 10;
    private static final int CONSUMER_COUNT = 5;

    public static void main(String[] args) {
        LinkedList<Integer> buffList = new LinkedList<Integer>();
        Producer producer = new Producer(buffList);
        Consumer consumer = new Consumer(buffList);
        for (int i = 0; i < CONSUMER_COUNT; i++) {
            new Thread(consumer).start();
        }
        new Thread(producer).start();
    }

    static class Producer implements Runnable {
        private LinkedList<Integer> list = null;

        public Producer(LinkedList<Integer> list) {
            this.list = list;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (list) {
                    while (list.size() > BUFF_SIZE) {// 用if判断是个坑
                        try {
                            System.out.println("Producer:"
                                    + Thread.currentThread().getId() + "wait");
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    Random random = new Random();
                    int i = random.nextInt();
                    System.out.println("Producer:"
                            + Thread.currentThread().getId() + "增加了内容为" + i
                            + "的节点");
                    list.add(i);
                    list.notifyAll();
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer implements Runnable {
        private LinkedList<Integer> list = null;

        public Consumer(LinkedList<Integer> list) {
            this.list = list;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (list) {
                    while (list.isEmpty()) {// 用if判断是个坑
                        System.out.println("Consumer"
                                + Thread.currentThread().getId() + "wait");
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Consumer:"
                            + Thread.currentThread().getId() + "移除了内容为"
                            + list.remove() + "的节点");
                    list.notifyAll();
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
volatile

volatile什么时候使用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【JAVA 线程】 线程 进程:是一个正在执行中的程序。每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者...
    Rtia阅读 2,784评论 2 20
  • 下面是我自己收集整理的Java线程相关的面试题,可以用它来好好准备面试。 参考文档:-《Java核心技术 卷一》-...
    阿呆变Geek阅读 14,911评论 14 507
  • Java中的线程(多线程),本篇主要讲一下线程的概念和基本操作以及各个方法的用法等;首先在了解线程前我们必须应该知...
    星星_点灯阅读 384评论 0 0
  • 一、线程与进程 线程定义 进程中执行的一个代码段,来完成不同的任务 组成:线程ID,当前指令指针(PC),寄存器集...
    Ada54阅读 1,120评论 1 1
  • 今天课间,有同学在拿手机看《人民的名义》,问起,班里有一半多的同学都在追这部剧,男孩女孩都有。班里的孩子基...
    秋水长天碧阅读 121评论 0 0