java多线程看这一篇就够啦
程序员文章站
2022-06-05 19:50:33
...
概念
process 进程 thread线程
程序是静态的,是指令和数据的有序结合
进程是执行程序的一次过程是系统资源分配的单位
线程是CPU执行和调度的单位
创建线程的三种方法
方法一:继承thread类,重写run方法,main主函数调用start开启线程
(不建议使用,OOP单继承局限性)
//继承thread类
public class thread extends Thread{
@Override
//重写run方法
public void run() {
for (int i = 0; i<200; i++){
System.out.println("这是run线程"+i);
}
}
public static void main(String[] args) {
thread thread1 = new thread();
//调用start
thread1.start();
for (int i = 0;i<200;i++){
System.out.println("这是main线程"+i);
}
}
}
方法二:实现runnable接口(其实上面的thread也实现了这个接口),重写run方法,main主函数调用start开启线程
(建议使用,避免单继承局限性,灵活使用,方便同一个对象被多个线程使用)
//实现runnable接口
public class runn implements Runnable{
@Override
//run方法线程体
public void run() {
for (int i = 0; i<200; i++){
System.out.println("这是run线程"+i);
}
}
public static void main(String[] args) {
//创建runnable接口实现类对象
runn runn = new runn();
//创建线程对象
Thread thread = new Thread(runn);
//通过线程对象开启线程(代理)
thread.start();
//其实上面两句等价于
new Thread(runn).start();
for (int i = 0;i<200;i++){
System.out.println("这是main线程"+i);
}
}
}
例子1:多个线程操作同一个资源的情况下,线程是不安全的,数据紊乱。
public class unsafe implements Runnable{
private int ticket= 10;
@Override
public void run() {
while (true){
if (ticket<=0){
break;
}
try {
//模拟延迟
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ "拿到了第" + ticket-- + "张票");
}
}
public static void main(String[] args) {
unsafe unsafe = new unsafe();
new Thread(unsafe,"小明").start();
new Thread(unsafe,"小蓝").start();
new Thread(unsafe,"小黄").start();
}
}
输出结果为
例子2:龟兔赛跑
public class rabbit implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 0;i<=100;i++){
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子")){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
private boolean gameOver(int steps){
//判断是否有胜利者
if (winner!= null){
return true;
}else {
if (steps>=100){
winner = Thread.currentThread().getName();
System.out.println("winner is "+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
rabbit rabbit = new rabbit();
new Thread(rabbit,"乌龟").start();
new Thread(rabbit,"兔子").start();
}
}
方法三:实现callable接口,需要返回值类型,重写call方法(需要抛出异常)
public class call1 implements Callable {
@Override
public Object call() throws Exception {
for (int x = 0; x < 100; x++) {
System.out.println(Thread.currentThread().getName() + ":" + x);
}
return null;
}
public static void main(String[] args) {
//创建线程池对象
ExecutorService pool = Executors.newFixedThreadPool(2);
//提交任务
pool.submit(new call1());
pool.submit(new call1());
//关闭线程池
pool.shutdown();
}
}
线程的一些常用方法
线程的停止
建议让线程自己停下来
可以使用一个标志位来停止变量当 flag=false 时,则终止线程
不要使用stop,destory等过时方法或JDK不建议使用的方法
public class testStop implements Runnable{
private boolean flag=true;
@Override
public void run() {
int i =0;
while (flag){
System.out.println("线程在run...."+i);
}
}
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
testStop stop = new testStop ();
new Thread(stop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main线程在run...."+i);
if (i == 900){
stop.stop();
System.out.println("线程停止了");
}
}
}
}
线程休眠——sleep
可以指定当前线程阻塞的毫秒数,所以可以模拟网络延时,倒计时等
日常可以用sleep放大线程一些问题的发生性
每个对象都有一个锁,sleep不会释放锁
模拟网络延时
别说我偷懒,这里确实用到了sleep
public class TestSleep1 implements Runnable {
private int ticket = 10;
@Override
public void run () {
while (true) {
if (ticket <= 0) {
break;
}
try {
//模拟延迟
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- + "张票");
}
}
public static void main (String[]args){
com.andrew.thread.unsafe3 unsafe = new com.andrew.thread.unsafe3();
new Thread(unsafe, "小明").start();
new Thread(unsafe, "小蓝").start();
new Thread(unsafe, "小黄").start();
}
}
使用sleep每隔一秒获取系统时间
public class TestSleep2 {
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
Date date = new Date(System.currentTimeMillis());//获取当前时间
while (true){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());//更新当前时间
}
}
}
线程礼让——yield
线程礼让即A从运行状态,又变成就绪状态,这时候A和B又是同一起跑线继续跑
所以,线程礼让不一定成功
public class TestYield {
public static void main(String[] args) {
MyYield m =new MyYield();
new Thread(m,"A").start();
new Thread(m,"B").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//线程礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
线程强制执行——join
会造成线程阻塞
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("Join插队"+i+"次");
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 100; i++) {
System.out.println("main线程运行"+i+"次");
if (i==50){
thread.join();
}
}
}
}
观测线程状态——getState()
要注意线程死了之后无法再start()
public class TestLook {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程结束");
});
//观察状态
Thread.State state = thread.getState();
//NEW
System.out.println(state);
//观察启动后
//启动线程
thread.start();
state = thread.getState();
//RUN
System.out.println(state);
//只要不终止,就一直输出状态
while (state != Thread.State.TERMINATED){
Thread.sleep(100);
//更新线程状态
state = thread.getState();
//输出状态
System.out.println(state);
}
}
}
线程的优先级——setPriority
可以看到优先级高的先执行,但是这其实并不是绝对的,也有少部分不会这样(性能倒置)
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread a1 = new Thread(myPriority);
Thread a2 = new Thread(myPriority);
Thread a3 = new Thread(myPriority);
Thread a4 = new Thread(myPriority);
a1.start();
a2.setPriority(3);
a2.start();
a3.setPriority(Thread.MAX_PRIORITY);
a3.start();
a4.setPriority(7);
a4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
结果
main--->5
Thread-2--->10
Thread-0--->5
Thread-3--->7
Thread-1--->3
守护线程——Daemon
线程分为用户线程和守护线程
虚拟机会确保用户进程(main…)执行完毕
虚拟机不会确保守护进程(gc…)执行完毕
public class TestDaemon {
public static void main(String[] args) {
Daemon daemon = new Daemon();
Common common = new Common();
Thread thread = new Thread(daemon);
//默认是false
thread.setDaemon(true);
thread.start();
new Thread(common).start();
}
}
//守护线程
class Daemon implements Runnable{
@Override
public void run() {
while (true){
System.out.println("我是守护线程");
}
}
}
//用户线程
class Common implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是用户线程---》"+i);
}
System.out.println("我结束了");
}
}
线程同步机制
多个线程访问同一个对象就会产生队列,为了保证线程安全就产生了锁(synchronized)。
锁带来了安全,也带来了不便
1.一个线程持有锁会导致其他需要此锁的线程挂起
2.在多线程竞争下﹐加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
3.如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题.