多线程
进程:程序及其数据在处理机器上 顺序执行发生的活动。是程序在一个数据集合上运行的过程,是系统进行资源分配和调度的独立单位。
可以将一个运行的exe 理解成一个“”“进程” 受操作系统管理的基本运行单元。
线程:比如QQ.exe运行时就有多个子任务在同时运行。
多线程是异步的,线程被调用是随机的。
继承Thread 类实现run方法
实现Runnable接口 ,实现run方法。
特别的: Thread implements Runnable
1.2.3实例变量与线程安全
实例变量针对其他线程有共享和不共享之分
public class Mythread extends Thread {
private int count = 5;
public Mythread(String name) {
super();
this.setName(name);//设置线程名字
}
@Override
public void run() {
super.run();
while (count > 0) {
try {
Thread.sleep(1000);
count--;
System.out.println("当前线程名-->" + this.currentThread().getName() + "\t" + "当前数量count-->" + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class run {
public static void main(String[] args) {
Mythread a = new Mythread("A");
Mythread b = new Mythread("B");
Mythread c = new Mythread("C");
a.start();
b.start();
c.start();
}
}
加锁的这段代码称之为互斥区,
public class Mythread1 extends Thread{
private int count = 5;
@Override
synchronized public void run() {
super.run();
count--;
System.out.println("当前线程名-->" + this.currentThread().getName() + "\t" + "当前数量count-->" + count);
}
}
class run{
public static void main(String[] args) {
Mythread1 mythread1 = new Mythread1();
//它的构造方法
Thread a = new Thread(mythread1, "A");
Thread b = new Thread(mythread1, "B");
Thread c = new Thread(mythread1, "C");
Thread d = new Thread(mythread1, "D");
a.start();
b.start();
c.start();
d.start();
}
}
执行结果
当前线程名-->A 当前数量count-->4
当前线程名-->D 当前数量count-->3
当前线程名-->C 当前数量count-->2
当前线程名-->B 当前数量count-->1
getId()
判断线程是否停止状态
能停止线程的异常
使用return 停止线程
暂停线程恢复线程
表示该线程还可以恢复
守护线程
基础知识
进程: QQ.exe 运行起来的程序称之为一个进程。
线程:程序里,不同执行路径
run()方法,是串行执行
调用start()是并行执行
sleep() 让当前线程睡眠,
yield()让出一下cup,其他线程可不可以抢到cpu不管。
join(),保证所有线程按照顺序执行完。