Java多线程

1、进程:程序(任务)的执行过程,持有 资源(共享内存、共享文件)和线程。
2、线程:系统中最小的执行单元,同一个进程中有多个线程,线程共享进程的资源。
3、线程的交互:
多个线程需要之间通信才能工作,这种通信就是交互。
交互的方式:互斥、同步。
4、java语言对线程的支持主要体现在class:Thread和interface:Runnable上
它们都有公共方法run(),线程实际工作的代码在其中。
5、Java中常用的方法
6、如何正确的停止JAVA中的线程
(1),stop()方法:是不正确的停止线程的方法,新的代码不应该再用,只能出现在历史代码中
它会让线程:戛然而止、不知道完成了什么、不知道哪些工作还没有做、没有机会做清理的工作不安全。
(2),interrupt()方法:初衷并不是用于停止线程
If this thread is blocked in an invocation of the  wait() wait(long) , or  wait(long, int)  methods of the  Object  class, or of the  join() join(long) join(long, int) sleep(long) , or  sleep(long, int) , methods of this class, then its interrupt status will be cleared and it will receive an  InterruptedException .
If none of the previous conditions hold then this thread's interrupt status(interrupted(),isInterrupted()) will be set.
public static boolean interrupted()
public boolean isInterrupted()

(3),正确的停止方法:使用退出标志
******keepRunning即为退出标志********
public class ArmyRunnable implements Runnable {
//volatile保证了线程可以正确的读取其他线程写入的值
//可见性 ref JMM,happens-before原则
//退出标志
volatile boolean keepRunning=true;
@Override
public void run() {
while(keepRunning){
//发起5连击
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+"进攻对方 ["+i+"]次");
//让出了处理器时间,下次该谁进攻还不一定呢!
Thread.yield();
}
}
System.out.println(Thread.currentThread().getName()+"进攻结束!");
}
}
//线程停止
newobject.keepRunning = false;
7、争用条件
当多个线程同时共享访问一个数据(内存区域)时,每个线程都尝试操作该数据,从而导致数据被破坏(corrupted),这种现象称为争用条件。
8、互斥的实现:
synchronized(intrinsic lock) 使其它线程不能进入此代码块
9、同步的实现:
由于某些条件的不具备,使线程处于等待的状态;而在条件满足时,只要女主角发出一条消息唤醒其他线程。
方法:(1),wait()使线程处于等待;(2),notify()和notifyAll()唤醒线程;(1)与(2)必须在不同的线程中操作,是两个线程之间的操作。
10、扩展Java并发
(1),Java Memory Mode
JMM描述了Java线程如何通过内存进行交互
happens-before
synchronized,volatile & final
(2),Locks & Condition
Java锁机制和等待条件的高层实现
java.util.concurrent.locks
(3),线程安全性
原子性与可见性
java.util.concurrent.atomic
synchronized & volatile
DeadLocks
(4),多线程编程常用的交互模型
Producer-Consumer模型
Read-Write Lock模型
Future模型
Worker Thread 模型
(5),Java5中并发编程工具
java.util.concurrent
线程池ExecutorService
Callable & Future
BlockingQueue


总结于相关视频:http://www.imooc.com/learn/202

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值