介绍一下线程中基本的方法使用

线程睡眠sleep()

Thread.sleep(毫秒);我们可以通过sleep方法设置让线程睡眠。可以看到sleep是个静态方法

  1. public static native void sleep(long var0) throws InterruptedException;
  1. try {
  2. System.out.println(new Date().getSeconds());
  3. Thread.sleep(5000);
  4. System.out.println(new Date().getSeconds());
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }

setDaemon守护线程

非守护线程停止,那么守护线程自动退出

  1. public static void main(String[] args) {
  2. Thread thread1 = new Thread() {
  3. @Override
  4. public void run() {
  5. super.run();
  6. for(int i = 0; i < 5; i ++) {
  7. System.out.println("非守护线程");
  8. }
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. @Override
  13. public void run() {
  14. for(int i = 0; i < 200; i ++) {
  15. System.out.println("守护线程");
  16. }
  17. }
  18. };
  19. thread2.setDaemon(true);
  20. thread1.start();
  21. thread2.start();
  22. }

可以很明显的看到thread2本应该执行200次输出,但是这里只输出了几行。因为当thread1执行完毕后,thread2作为守护线程就自动停止了。

多线程join

如果执行了join方法,那么停止当前线程,先跑执行了join()的线程。相当于插队执行。如下,在执行thread2线程的时候,如果i==20的时候,则让thread1插队先执行

  1. public static void main(String[] args) {
  2. final Thread thread1 = new Thread() {
  3. @Override
  4. public void run() {
  5. super.run();
  6. for(int i = 0; i < 500; i ++) {
  7. System.out.println("thread1---" + i);
  8. }
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. @Override
  13. public void run() {
  14. for(int i = 0; i < 200; i ++) {
  15. if (i == 20) {
  16. try {
  17. //插队执行
  18. thread1.join();
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. System.out.println(i);
  24. }
  25. }
  26. };
  27. thread1.start();
  28. thread2.start();
  29. }

join()方法也可以传参数long 毫秒 join(毫秒)

表示让执行join的线程,插队执行XXX毫秒,过了时间后,两个线程交替执行

  1. public static void main(String[] args) {
  2. final Thread thread1 = new Thread() {
  3. @Override
  4. public void run() {
  5. super.run();
  6. for(int i = 0; i < 500; i ++) {
  7. System.out.println("thread1---" + i);
  8. }
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. @Override
  13. public void run() {
  14. for(int i = 0; i < 200; i ++) {
  15. if (i == 20) {
  16. try {
  17. //插队执行1毫秒
  18. thread1.join(1);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. System.out.println(i);
  24. }
  25. }
  26. };
  27. thread1.start();
  28. thread2.start();
  29. }

yeild 礼让线程

yeild会让出cpu,让其他线程执行

  1. public static void main(String[] args) {
  2. final Thread thread1 = new Thread() {
  3. @Override
  4. public void run() {
  5. super.run();
  6. for(int i = 0; i < 500; i ++) {
  7. System.out.println( getName() + "---" + i);
  8. }
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. @Override
  13. public void run() {
  14. for(int i = 0; i < 200; i ++) {
  15. if (i % 5 == 0) {
  16. Thread.yield();
  17. }
  18. System.out.println(getName() + "---" + i);
  19. }
  20. }
  21. };
  22. thread1.start();
  23. thread2.start();
  24. }

setPriority给线程设置优先级

默认优先级是5 最小1,最大10


越大优先级越高


  1. public static void main(String[] args) {
  2. final Thread thread1 = new Thread() {
  3. @Override
  4. public void run() {
  5. super.run();
  6. for(int i = 0; i < 500; i ++) {
  7. System.out.println( getName() + "---" + i);
  8. }
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. @Override
  13. public void run() {
  14. for(int i = 0; i < 500; i ++) {
  15. System.out.println(getName() + "---" + i);
  16. }
  17. }
  18. };
  19. //设置最大的线程优先级最大为10
  20. thread1.setPriority(Thread.MIN_PRIORITY);
  21. //设置最小的线程优先级,最小为1
  22. thread2.setPriority(Thread.MAX_PRIORITY);
  23. thread1.start();
  24. thread2.start();
  25. }

synchronized

同步代码块

当多线程并发,多段代码同时执行的时候。希望在执行其中代码的时候,cpu不切换线程

不用synchronized的情况

我们来看一下不用synchronized的情况会发生什么

  1. public class ThreadSynchronied {
  2. public static void main(String[] args) {
  3. final Say say = new Say();
  4. Thread thread1 = new Thread() {
  5. @Override
  6. public void run() {
  7. for (int i = 0 ; i < 10000 ; i ++) {
  8. say.say();
  9. }
  10. }
  11. };
  12. Thread thread2 = new Thread() {
  13. @Override
  14. public void run() {
  15. for (int i = 0 ; i < 10000 ; i ++) {
  16. say.say1();
  17. }
  18. }
  19. };
  20. //设置最大的线程优先级最大为10
  21. thread1.setPriority(Thread.MIN_PRIORITY);
  22. //设置最小的线程优先级,最小为1
  23. thread2.setPriority(Thread.MAX_PRIORITY);
  24. thread1.start();
  25. thread2.start();
  26. }
  27. }
  28. class Say {
  29. void say() {
  30. System.out.print("s ");
  31. System.out.print("a ");
  32. System.out.print("y ");
  33. System.out.print("h ");
  34. System.out.print("e ");
  35. System.out.print("l ");
  36. System.out.print("l ");
  37. System.out.println("o");
  38. }
  39. void say1() {
  40. System.out.print("1 ");
  41. System.out.print("2 ");
  42. System.out.print("3 ");
  43. System.out.print("4 ");
  44. System.out.print("5 ");
  45. System.out.print("6 ");
  46. System.out.print("7 ");
  47. System.out.println("8");
  48. }
  49. }

我们发现有些输出并没有打印全,在执行线程thread1的过程中,cpu被thread2抢占。这种情况下,肯定是不符合我们的业务逻辑的。所以我们要保证线程执行了一个完整的方法后,cpu才会被其他线程抢占

使用synchronized

  1. public class ThreadSynchronied {
  2. public static void main(String[] args) {
  3. final Say say = new Say();
  4. Thread thread1 = new Thread() {
  5. @Override
  6. public void run() {
  7. for (int i = 0 ; i < 10000 ; i ++) {
  8. say.say();
  9. }
  10. }
  11. };
  12. Thread thread2 = new Thread() {
  13. @Override
  14. public void run() {
  15. for (int i = 0 ; i < 10000 ; i ++) {
  16. say.say1();
  17. }
  18. }
  19. };
  20. //设置最大的线程优先级最大为10
  21. thread1.setPriority(Thread.MIN_PRIORITY);
  22. //设置最小的线程优先级,最小为1
  23. thread2.setPriority(Thread.MAX_PRIORITY);
  24. thread1.start();
  25. thread2.start();
  26. }
  27. }
  28. class Say {
  29. String s = "hahaah";
  30. void say() {
  31. synchronized (s) {
  32. System.out.print("s ");
  33. System.out.print("a ");
  34. System.out.print("y ");
  35. System.out.print("h ");
  36. System.out.print("e ");
  37. System.out.print("l ");
  38. System.out.print("l ");
  39. System.out.println("o");
  40. }
  41. }
  42. void say1() {
  43. synchronized (s) {
  44. System.out.print("1 ");
  45. System.out.print("2 ");
  46. System.out.print("3 ");
  47. System.out.print("4 ");
  48. System.out.print("5 ");
  49. System.out.print("6 ");
  50. System.out.print("7 ");
  51. System.out.println("8");
  52. }
  53. }
  54. }

使用synchronized同步代码块后,就发现不会出现上述情况了

同步方法

  1. public class ThreadSynchroniedMethod {
  2. public static void main(String[] args) {
  3. final Say say = new Say();
  4. Thread thread1 = new Thread() {
  5. @Override
  6. public void run() {
  7. for (int i = 0 ; i < 10000 ; i ++) {
  8. say.say();
  9. }
  10. }
  11. };
  12. Thread thread2 = new Thread() {
  13. @Override
  14. public void run() {
  15. for (int i = 0 ; i < 10000 ; i ++) {
  16. say.say1();
  17. }
  18. }
  19. };
  20. //设置最大的线程优先级最大为10
  21. thread1.setPriority(Thread.MIN_PRIORITY);
  22. //设置最小的线程优先级,最小为1
  23. thread2.setPriority(Thread.MAX_PRIORITY);
  24. thread1.start();
  25. thread2.start();
  26. }
  27. }
  28. class Say {
  29. //在方法上加锁
  30. static synchronized void say() {
  31. System.out.print("s ");
  32. System.out.print("a ");
  33. System.out.print("y ");
  34. System.out.print("h ");
  35. System.out.print("e ");
  36. System.out.print("l ");
  37. System.out.print("l ");
  38. System.out.println("o");
  39. }
  40. static void say1() {
  41. synchronized (Say.class) {
  42. System.out.print("1 ");
  43. System.out.print("2 ");
  44. System.out.print("3 ");
  45. System.out.print("4 ");
  46. System.out.print("5 ");
  47. System.out.print("6 ");
  48. System.out.print("7 ");
  49. System.out.println("8");
  50. }
  51. }
  52. }

同步方法指的就是在方法上加锁

静态同步方法的所对象是该类的字节码对象

非静态的同步方法锁对象是this

多个线程使用同一资源锁,容易造成死锁

什么是死锁?

  1. 死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。

线程安全类

Vector

StringBuffer

HashTable

线程不安全

ArrayList

StringBuilder

HashSet

java.util.Collections中有synchronizedList等方法,支持我们把线程不安全的集合转成线程安全的

学习笔记

多次启动一个线程是非法的

java中多线程 - 多线程中的基本方法的更多相关文章

  1. Java线程和多线程(二)——对象中的wait,notify以及notifyAll方法

    Java对象中的wait,notify以及notifyAll方法 在Java的Object类中包含了3个final的方法,这三个方法允许线程来交流资源是否被锁定.这三个方法就是wait(),notif ...

  2. java多线程中wait/notify/sleep/join/yield方法以及多线程的六种状态

    刚开始学线程的时候也是被这几个方法搞的云里雾里的,尤其是一开始看的毕老师的视频,老师一直在强调执行权和执行资格,看的有点懵逼,当然不是说毕老师讲的不好,就是自己有点没听明白,后来复习看了一些其他的博客 ...

  3. Java多线程中join、yield、sleep方法详解

    在Java多线程编程中,Thread类是其中一个核心和关键的角色.因此,对该类中一些基础常用方法的理解和熟练使用是开发多线程代码的基础.本篇主要总结一下Thread中常用的一些静态方法的含义及代码中的 ...

  4. 详细分析 Java 中实现多线程的方法有几种?(从本质上出发)

    详细分析 Java 中实现多线程的方法有几种?(从本质上出发) 正确的说法(从本质上出发) 实现多线程的官方正确方法: 2 种. Oracle 官网的文档说明 方法小结 方法一: 实现 Runnabl ...

  5. Java多线程入门中几个常用的方法

    一.currentThread()方法 currentThread方法就是返回当前被调用的线程. 该方法为一个本地方法,原码如下: /** * Returns a reference to the c ...

  6. 黑马程序员_ JAVA中的多线程

    ------- android培训.java培训.期待与您交流! ---------- 尽管线程对象的常用方法可以通过API文档来了解,但是有很多方法仅仅从API说明是无法详细了解的. 本来打算用一节 ...

  7. 【转】Java多线程编程中易混淆的3个关键字( volatile、ThreadLocal、synchronized)总结

    概述 最近在看<ThinKing In Java>,看到多线程章节时觉得有一些概念比较容易混淆有必要总结一下,虽然都不是新的东西,不过还是蛮重要,很基本的,在开发或阅读源码中经常会遇到,在 ...

  8. java中的多线程——进度1

    import java.util.*;public static void main(String[] args) {/*final可以修饰类,方法,变量.final修饰的类不可以被继承.final修 ...

  9. JAVA并发七(多线程环境中安全使用集合API)

    在集合API中,最初设计的Vector和Hashtable是多线程安全的.例如:对于Vector来说,用来添加和删除元素的方法是同步的.如果只有一个线程与Vector的实例交互,那么,要求获取和释放对 ...

  10. Java多线程编程中Future模式的详解

    Java多线程编程中,常用的多线程设计模式包括:Future模式.Master-Worker模式.Guarded Suspeionsion模式.不变模式和生产者-消费者模式等.这篇文章主要讲述Futu ...

随机推荐

  1. Anaconda、TensorFlow安装和Pycharm配置详细教程,亲测有效!

    目录 1.Anaconda下载与安装 2.Anaconda安装成功与否测试 3.安装python 4.检查TensorFlow环境添加成功与否 5.TensorFlow安装 6.测试TensorFlo ...

  2. Python网络爬虫实战(五)批量下载B站收藏夹视频

    我们除了爬取文本信息,有的时候还需要爬媒体信息,比如视频图片音乐等.就拿B站来说,我的收藏夹内的视频可能随时会失效,所以把它们下载到本地是非常保险的一件事. 对于这种大量列表型的数据,可以猜测B站收藏 ...

  3. vue中关于滚动条的那点事

    vue中关于滚动条的那点事 不知道你有没有遇到过这种情况,有时当页面切换时,滚动条不在页面的顶端.最近半路加入一个项目,就遇到这种情况.(若只是为了解决此问题,可直接翻到最下方)下面谈谈解决此问题的过 ...

  4. 站内搜索(ELK)之数据目录

    在使用elasticsearch建设站内搜索时,随着数据不断丰富,为了数据管理更加精细化,必须建立并实时维护“数据目录”(在程序设计中对应的叫法“数据字典”). 数据目录需要包含以下几个维度:数据名称 ...

  5. redis分布式锁-自动超时锁(在用)

    1.加锁代码结构 2.解锁代码结构 3.java实例 4.测试类 5.测试日志 加锁代码结构 def acquire_lock_with_timeout(conn,lockname,acquire_t ...

  6. Linux mint 启动文本模式(不启动图形界面)

    Linux Mint 系统用了很久,很顺手,赞一个! 有一天想同时运行多个虚拟机linux系统做实验,想着只启动文本模式可以省点内存资源,结果试了多种方法都不成功,网上现有针对Ubuntu原版和Cen ...

  7. ubuntu13启动屏幕亮度0解决方法

    在终端输入: sudo gedit /etc/default/grub 找到 GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" GRUB_CMDL ...

  8. volatile 关键字的作用

    简介Java 语言提供了一种稍弱的同步机制,即 volatile 变量,用来确保将变量的更新操作通知到其他线程.volatile 变量具备两种特性:变量可见性.禁止重排序. 作为同步锁在访问 vola ...

  9. Python爬虫(三):BeautifulSoup库

    BeautifulSoup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库,它能够将 HTML 或 XML 转化为可定位的树形结构,并提供了导航.查找.修改功能,它会自动将输入 ...

  10. vmware上安装centos7虚拟机

    1.1 Linux 的安装 安 装 采 用 在 虚 拟 机 中 安 装 , 以 方 便 不 同 班 级 授 课 时 , 需 要 重 复 安装的情况. 1.1.1 配置虚拟机 1. 在 VMware W ...