一、 线程和多线程
- 线程:不同的功能同时运行,每一次执行就是一个线程;
- 进程:打开软件运行,正在执行的叫进程;
- 程序:硬盘上的文件;
- 线程的结构:CPU、代码、处理
- 线程的状态:
二、创建线程
- 继承
Thread
类创建线程
package com.test;
import java.util.Date;
public class TestThread{
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
TestThread2 testThread2 = new TestThread2();
testThread1.start();
testThread2.start();
}
}
class TestThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("1的第"+i+"次北京时间:"+new Date());
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class TestThread2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("2的第"+i+"次北京时间:"+new Date());
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
1的第0次北京时间:Wed Mar 03 14:47:54 CST 2021
2的第0次北京时间:Wed Mar 03 14:47:54 CST 2021
2的第1次北京时间:Wed Mar 03 14:47:56 CST 2021
1的第1次北京时间:Wed Mar 03 14:47:57 CST 2021
2的第2次北京时间:Wed Mar 03 14:47:58 CST 2021
1的第2次北京时间:Wed Mar 03 14:48:00 CST 2021
- 实现
Runnable
接口创建线程
package com.test;
public class TestRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 2; i++) {
System.out.println("第一"+i+"次来了");
}
}
public static void main(String[] args) {
TestRunnable testRunnable = new TestRunnable();
testRunnable.run();
Thread thread = new Thread(testRunnable)
thread.start();
}
}
第一0次来了
第一1次来了
- 两者适用条件
Runnable
:已经继承了其他类Thread
:代码简洁
三、线程的基本控制
- 线程的启动
start()
:送到CPU排对,处于就绪状态
- 线程的调度
- 设置优先级:
void setPriority(int o)
可设置1-10级 - 获取优先级:
int getPriority()
默认5级 - 改变线程状态:
sleep()
- 让一点,不改变状态
yield()
- 结束线程
- 线程运行完
- 强制结束线程:
interrupt()
和stop()
- 挂起线程
- 改变状态重新排对:
sleep()
wait()
和[notify()
或notifyAll()
唤醒等待的线程]join()
四、线程的互斥
- 互斥问题:同时取钱的情况不允许就是互斥;
- 实现互斥:
synchronized(this){}
一次只能通过一个
五、线程同步(考题会涉及)
- 与线程互斥是一样的
注意:程序填空题(5-10分)