JavaSE学习——多线程

张开发
2026/4/18 7:29:30 15 分钟阅读

分享文章

JavaSE学习——多线程
进程是资源分配的最小单位线程是CPU调度的最小单位。java的一个main方法里在运行的时候实际上还调用了其他的线程只不过main是主线程。线程的关键字是Thread它在调用的时候需要实现其run函数可以使用Lambda表达式并且需要进行”激活“使用start方法例如public static void main(String[] args) { Thread thread new Thread(()-{ System.out.println(线程Thread.currentThread().getName()); System.out.println(计算0-100000之间所有数字的和.....); int sum 0; for(int i 0; i 100000; i){ sumi; } System.out.printf(结果是%d,sum); }); thread.start(); System.out.println(主线程); }下面的实例可以清晰的看出来两个进程在交替进行还有一个方法是run它和start的区别是run相当于在main方法里面去运行(在当前线程去执行)而不是创建一个线程比如;thread1.run(); thread2.run();此外还有sleep方法手动使得线程暂时休眠特定时间正常情况下其他情形也会让线程暂时休眠比如等待用户输入控制台的Scanner方法下面的代码就是让线程停留1s:System.out.println(l); Thread.sleep(1000); System.out.println(h); Thread.sleep(1000); System.out.println(w); Thread.sleep(1000); System.out.println(520);现在每经过250毫秒输出一下上面线程的状态public static void main(String[] args) { Threadthread new Thread(()-{ try{ System.out.println(l); Thread.sleep(1000); System.out.println(h); Thread.sleep(1000); System.out.println(w); Thread.sleep(1000); System.out.println(520); } catch (InterruptedException e) { throw new RuntimeException(e); } }); thread.start(); Thread test new Thread(()-{ while(true){ try{ Thread.sleep(250); System.out.println(thread.getState()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); }getState里面的状态是一个枚举类里面有NEW, RUNNABLE(运行或等待资源), BLOCKED阻塞WAITINGTIMED_WAITINGTERMINAL是终端结束的意思。现在开始运行一下下面的代码import java.util.concurrent.atomic.AtomicInteger; public class Main{ public static void main(String[] args) { AtomicInteger a new AtomicInteger(); Thread thread new Thread(()-{ try{ System.out.println(l); Thread.sleep(1000); System.out.println(h); Thread.sleep(1000); System.out.println(w); Thread.sleep(1000); System.out.println(520); for (int i 0; i 100000000; i) { a.set(i 1); } System.out.println(结束); } catch (InterruptedException e) { throw new RuntimeException(e); } }); thread.start(); new Thread(()-{ while(true){ try{ Thread.sleep(250); System.out.println(thread.getState()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } }查看输出可以看到上面的输出中前期几乎都在TIMED_WAITING因为我们在手动进行休眠之后有一个RUNNABLE因为在运行for循环,最后是TERMINATED因为子进程结束了强制终止一个线程stop方法但是已经被JAVA21之后废除了。最后看一个程序它的输出public class Main{ private static int value 0; public static void main(String[] args) throws InterruptedException { Thread t1 new Thread(() - { for (int i 0; i 10000; i) value; System.out.println(线程1完成); }); Thread t2 new Thread(() - { for (int i 0; i 10000; i) value; System.out.println(线程2完成); }); t1.start(); t2.start(); Thread.sleep(1000); // 主线程停止1秒保证两个线程执行完成 System.out.println(value); } }很奇怪结果竟然不是20000原因因为 value 不是原子操作多线程同时修改出现了数据覆盖所以结果 20000在 CPU 底层它分为3 个步骤读取value 的值计算value 1写回value这叫非原子操作比如这种情况线程 1 读到 value 100线程 2 也读到 value 100线程 1 算成 101写回 →101线程 2 也算成 101写回 →101明明加了两次结果只加了 1 次这就叫线程不安全、数据丢失。

更多文章