多线程
文章平均质量分 55
大秦樗里疾
樗里疾,能打仗能外交。小码农,能写代码能写文章。
展开
-
重学Java之线程同步
线程同步主要是为了防止多线程情况下,资源访问冲突。举个栗子,卖票,还有 2 张票,A B 两个线程同时操作,A 线程把剩余的2张票都卖了,此时 B 线程已经执行完判断是否有票的逻辑,B 也卖了 2 张票。这显然是不对的。多线程情况下,在对数据操作时要确保线程安全。于是有了线程同步机制,用来解决资源共享问题。线程同步机制 就是在给定范围内给资源加上一把锁,只允许一个线程访问资源。1.线程不安全以卖票(奶茶)为例,总数固定,每次减1 ,3个线程同时操作,public class TestSynch原创 2021-08-04 10:11:24 · 97 阅读 · 0 评论 -
重学Java之创建线程
创建线程有 3 种方法:继承Thread实现 Runnable 接口使用 Callable 和 FutureTask继承Thread编写一个 MyThread 类,继承 Thread ,重写 run() 方法,run() 方法就是具体要执行的任务。调用 start() 方法来执行线程。public class TestThread { public static void main(String[] args) throws InterruptedException {原创 2021-08-03 11:05:32 · 82 阅读 · 0 评论 -
重学Java之线程的 join 方法
线程的 join 方法 API 说明,Waits for this thread to die.An invocation of this method behaves in exactly the same way as the invocationjoin(0)Throws:InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current原创 2021-08-03 17:02:51 · 123 阅读 · 0 评论 -
重学Java之线程的中断
开启线程都知道了,怎么中断一个线程呢?这里的中断也叫终止、停止,意思都是停止一个正在运行的线程。1.设置中断标志位在线程的执行逻辑中添加标志位判断,需要中断线程时,修改该标志位,让线程执行逻辑结束。public class StopThreadTest { public static void main(String[] args) throws InterruptedException { FThread fThread = new FThread();原创 2021-08-03 19:45:25 · 118 阅读 · 0 评论