哈喽!大家好,我是小简。今天开始学习《Java-线程》,此系列是我做的一个 “Java 从 0 到 1 ” 实验,给自己一年左右时间,按照我自己总结的 Java-学习路线,从 0 开始学 Java 知识,并不定期更新所学笔记,期待一年后的蜕变吧!
程序
程序是为完成特定任务、用某种语言编写的一-组指令的集合。简单的说:就是我们写的代码
进程
进程是指运行中的程序,启动一个进程,操作系统就会为该进程分配内存空间。
进程是程序的一次执行过程,或是正在运行的一个程序。是动态过程:有它自身的产生、存在和消亡的过程。
线程
线程由进程创建的,是进程的一个实体,一个进程可以拥有多个线程
并发
同一个时刻,多个任务交替执行,造成一种”貌似同时”的错觉,简单的说, 单核 cpu 实现的多任务就是并发。例如:Tom 边开车边接电话
并行
同一个时刻,多个任务同时执行。多核 cpu 可以实现并行。例如:Tom 开车 ,Jack 接电话
说明
package com.jwt.threaduse;
public class Thread01 {
public static void main(String[] args) {
Cat cat = new Cat();
cat.start();//start 调用了 start0(),start0() 调用了 run()
}
}
class Cat extends Thread{
private int count = 0;
@Override
public void run() {
while (true) {
System.out.println("喵喵, 我是小猫咪" + (++count) + " 线程名=" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 10){
break;
}
}
System.out.println("线程结束。。。");
}
}
package com.jwt.threaduse;
public class Thread02 {
//请编写程序,该程序可以每隔1秒在控制台输出"嗷嗷, 我是小老虎" ,当输出10次后,自动退出。
public static void main(String[] args) {
Tiger tiger = new Tiger();
//tiger.start() 没有这个方法
Thread thread = new Thread(tiger);//代理
thread.start();
}
}
class Tiger implements Runnable{
private int count = 0;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("嗷嗷, 我是小老虎"+ (++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程结束。。。");
}
}
实现 Runnable 接口创建线程底层使用了设计模式[代理模式]
代码模拟实现 Runnable 接口开发线程的机制
package com.jwt.threaduse;
public class Thread02 {
public static void main(String[] args) {
Dog dog = new Dog();
ThreadProxy threadProxy = new ThreadProxy(dog);
threadProxy.start();
}
}
class Animal {
}
class Dog extends Animal implements Runnable {
@Override
public void run() {
System.out.println("小狗汪汪叫....");
}
}
//线程代理类, 模拟了一个极简的Thread类
class ThreadProxy implements Runnable {
private Runnable target = null;//属性,类型是Runnable
@Override
public void run() {
if (target != null) {
target.run();//动态绑定(运行类型Tiger)
}
}
public ThreadProxy(Runnable target) {//构造函数
this.target = target;
}
public void start() {
start0();//这个方法时真正实现多线程方法
}
public void start0() {
run();
}
}
package com.jwt.threaduse;
public class Thread03 {
// 请编写一个程序,创建两个线程,
// 一个线程每隔1秒输出 "hello" ,输出10次,退出
// 一个线程每隔1秒输出"hi",输出5次退出。
public static void main(String[] args) {
T1 t1 = new T1();
T2 t2 = new T2();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
thread1.start();
thread2.start();
}
}
class T1 implements Runnable{
private int count = 0 ;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("hello" + (++count) + " 线程名:" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class T2 implements Runnable{
private int count = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("hi"+ (++count) + " 线程名:" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
编程模拟三个售票窗口共同售票 100 张,分别使用继承 Thread 和实现 Runnable 方式,并分析有什么问题?
package com.jwt.threaduse;
public class SellTicket {
public static void main(String[] args) {
//使用Thread 方式
SellTicket01 sellTicket01 = new SellTicket01();
SellTicket01 sellTicket02 = new SellTicket01();
SellTicket01 sellTicket03 = new SellTicket01();
sellTicket01.start();
sellTicket02.start();
sellTicket03.start();
//实现接口方式
// SellTicket02 sellTicket04 = new SellTicket02();
// Thread thread01 = new Thread(sellTicket04);
// Thread thread02 = new Thread(sellTicket04);
// Thread thread03 = new Thread(sellTicket04);
// thread01.start();
// thread02.start();
// thread03.start();
}
}
//使用Thread 方式
class SellTicket01 extends Thread {
private static int ticketNum = 20;//static 让多个线程共享ticketNum
@Override
public void run() {
while(true){
System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票 "+"剩余票数" + (--ticketNum));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticketNum <= 0) {
System.out.println("窗口" + Thread.currentThread().getName() + "售票结束...");
break;
}
}
}
}
//实现接口方式
class SellTicket02 implements Runnable{
private static int ticketNum = 20;//static 让多个线程共享ticketNum
@Override
public void run() {
while(true){
System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票 "+"剩余票数" + (--ticketNum));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticketNum <= 0) {
System.out.println("窗口" + Thread.currentThread().getName() + "售票结束...");
break;
}
}
}
}
问题总结:会出现多个窗口卖同一张票的情况,因为线程 1 还未减 1 时,线程 2 也开始执行了,就会造成线程 1 和 线程 2 返回的剩余票数相同。继续看下去这个问题将会得到解决。
例子🌰:启动一个线程,要求在 main 线程中去停止线程,请编程实现。
package com.jwt.threaduse;
public class ThreadExit {
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
Thread thread = new Thread(test);
thread.start();
//5s后退出
Thread.sleep(5000);
test.setLoop(false);
}
}
class Test implements Runnable{
private boolean loop = true;
@Override
public void run() {
while (loop) {
System.out.println("Test 运行中");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程结束");
}
public void setLoop(boolean loop) {
this.loop = loop;
}
}
package com.jwt.threaduse;
public class ThreadMethod01 {
public static void main(String[] args) throws InterruptedException {
ThreadDemo threadDemo = new ThreadDemo();
//设置线程名
threadDemo.setName("简简");
//得到线程名
System.out.println("线程名:" + threadDemo.getName());
//设置优先级
threadDemo.setPriority(Thread.MIN_PRIORITY);
//开启线程
threadDemo.start();
//输出优先级
System.out.println("优先级:"+threadDemo.getPriority());//当前线程优先级
System.out.println("默认优先级:"+Thread.currentThread().getPriority());//默认优先级
//测试interrupt
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("hi"+i);
}
//中断休眠的线程,线程运行5次,休眠20秒,打印5个hi就中断休眠
threadDemo.interrupt();
}
}
class ThreadDemo extends Thread{
@Override
public void run() {
while (true) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "运行中。。。");
}
try {
System.out.println("休眠中。。。");
Thread.sleep(20000);//休眠20秒
} catch (InterruptedException e) {
//当设线程执行到一个interrupt 万法时,就会catch 一个异常,可以加入自己的业务代码
System.out.println(Thread.currentThread().getName() + "被 interrupt 了");
}
}
}
}
例子🌰:
package com.jwt.threaduse;
public class ThreadMethod02 {
public static void main(String[] args) throws InterruptedException {
T t = new T();
t.start();
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
System.out.println("主线程:hi"+i);
if (i==5){
System.out.println("主线程让子线程先运行");
// Thread.yield();不一定能让成功
t.join();
System.out.println("子线程运行完毕,主线程接着运行");
}
}
}
}
class T extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程:hello"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
例子🌰:一个主线程,一个子线程,将子线程设置成守护线程,一旦主线程结束,守护线程自动结束。
package com.jwt.threaduse;
public class ThreadMethod03 {
public static void main(String[] args) throws InterruptedException {
MyDaemonThread myt = new MyDaemonThread();
myt.setDaemon(true);//设置守护线程
myt.start();
for (int i = 0; i < 5; i++) {
System.out.println("小简辛苦写代码。。。");
Thread.sleep(1000);
}
}
}
class MyDaemonThread extends Thread{
@Override
public void run() {
for (;;){//无限循环
System.out.println("小明和小红开心聊天。。。");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.jwt.threaduse;
public class ThreadState_ {
public static void main(String[] args) throws InterruptedException {
Td t = new Td();
System.out.println(t.getName() + " 状态" + t.getState());
t.start();
while (Thread.State.TERMINATED != t.getState()) {
System.out.println(t.getName() + " 状态" + t.getState());
Thread.sleep(500);
}
System.out.println(t.getName() + " 状态" + t.getState());
}
}
class Td extends Thread {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("hi " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
synchronized (对象) {//得到对象的锁,才能操作同步代码
//需要被同步代码;
}
public synchronized void m (String name){
//需要被同步的代码
}
使用互斥锁来解决售票问题
实现的步骤:
方法1:代码块加锁
package com.jwt.threaduse;
public class SellTicket {
public static void main(String[] args) {
//实现接口方式
SellTicket02 sellTicket04 = new SellTicket02();
Thread thread01 = new Thread(sellTicket04);
Thread thread02 = new Thread(sellTicket04);
Thread thread03 = new Thread(sellTicket04);
thread01.start();
thread02.start();
thread03.start();
}
}
//实现接口方式
class SellTicket02 implements Runnable{
private int ticketNum = 20;//static 让多个线程共享ticketNum
private boolean loop = true;//控制run 方法变量
@Override
public void run() {
while(loop){
synchronized (this) {
if (ticketNum <= 0) {
System.out.println("窗口" + Thread.currentThread().getName() + "售票结束...");
loop =false;
break;
}
System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票 "+"剩余票数" + (--ticketNum));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
方法2:方法加锁
package com.jwt.threaduse;
public class SellTicket {
public static void main(String[] args) {
//实现接口方式
SellTicket02 sellTicket04 = new SellTicket02();
Thread thread01 = new Thread(sellTicket04);
Thread thread02 = new Thread(sellTicket04);
Thread thread03 = new Thread(sellTicket04);
thread01.start();
thread02.start();
thread03.start();
}
}
//实现接口方式
class SellTicket02 implements Runnable{
private static int ticketNum = 20;//static 让多个线程共享ticketNum
private boolean loop = true;//控制run 方法变量
public synchronized void sell(){
if (ticketNum <= 0) {
System.out.println("窗口" + Thread.currentThread().getName() + "售票结束...");
loop =false;
return;
}
System.out.println("窗口" + Thread.currentThread().getName() + " 售出一张票 "+"剩余票数" + (--ticketNum));
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(loop){
sell();
}
}
}
注意:
多个线程都占用了对方的锁资源,但不肯相让,导致了死锁,在编程是一定要避免死锁的发生。
妈妈:你先完成作业,才让你玩手机 小明:你先让我玩手机,我才完成作业
例子🌰:
package com.jwt.threaduse;
public class DeadLock_ {
public static void main(String[] args) {
//模拟死锁现象
DeadLockDemo A = new DeadLockDemo(true);
A.setName("A 线程");
DeadLockDemo B = new DeadLockDemo(false);
B.setName("B 线程");
A.start();
B.start();
}
}
class DeadLockDemo extends Thread {
static Object o1 = new Object();// 保证多线程,共享一个对象,这里使用static
static Object o2 = new Object();
boolean flag;
public DeadLockDemo(boolean flag) {//构造器
this.flag = flag;
}
@Override
public void run() {
//下面业务逻辑的分析
//1. 如果flag 为T, 线程A 就会先得到/持有o1 对象锁, 然后尝试去获取o2 对象锁
//2. 如果线程A 得不到o2 对象锁,就会Blocked
//3. 如果flag 为F, 线程B 就会先得到/持有o2 对象锁, 然后尝试去获取o1 对象锁
//4. 如果线程B 得不到o1 对象锁,就会Blocked
if (flag) {
synchronized (o1) {//对象互斥锁, 下面就是同步代码
System.out.println(Thread.currentThread().getName() + " 进入1");
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " 进入2");
}
}
} else {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " 进入3");
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + " 进入4");
}
}
}
}
}
下面操作会释放锁
下面操作不会释放锁
package com.jwt.threaduse;
import java.util.Scanner;
public class Homework01 {
public static void main(String[] args) throws InterruptedException {
A a = new A();
B b = new B(a);
Thread thread = new Thread(b);
a.start();
thread.start();
}
}
class A extends Thread{
private boolean flag = true;
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
while (flag) {
//1-100
System.out.println((int)(Math.random()*100 + 1));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a线程退出");
}
}
class B implements Runnable{
private A a;
public B(A a) {
this.a = a;
}
@Override
public void run() {
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入指令:");
String s = scanner.nextLine();
if ("Q".equals(s)) {
a.setFlag(false);
System.out.println("b线程退出");
break;
}
}
}
}
package com.jwt.threaduse;
public class Homework02 {
//- (1)有 2 个用户分别从同一个卡上取钱(总额: 10000)
//- (2)每次都取 1000,当余额不足时,就不能取款了
//- (3)不能出现超取现象=》线程同步问题
public static void main(String[] args) {
Card card = new Card();
Thread thread1 = new Thread(card);
thread1.setName("User1");
Thread thread2 = new Thread(card);
thread2.setName("User2");
thread1.start();
thread2.start();
}
}
class Card implements Runnable{
private int money = 10000;
@Override
public void run() {
while (true){
//解读
//1.这里使用synchronized 实现了线程同步
//2.当多个线程执行到这里时,就会去争夺this对象锁
//3.哪个线程争夺到(获取)this对象锁, 就执行synchronized 代码块,执行完后, 会释放this对象锁
//4.争夺不到this对象锁,就bLocked ,准备继续争夺
//5.this对象锁是非公平锁
synchronized (this) {
money = money - 1000;
if (money < 1000) {
System.out.println("余额不足");
break;
}
System.out.println(Thread.currentThread().getName() + "取走了1000" + "剩余" + money);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}