Java多线程复习

CyclicBarrier详解:https://blog.csdn.net/qq_38293564/article/details/80558157

 

线程的主体类需要 继承Thread类 或 实现Runnable(Callable)借口 来完成定义

1.继承Thread类

线程启动的主方法是需要覆写Thread类中的run()方法实现

class 类名 extends Thread{
    属性...;
    方法...;

    @Override
    public void run(){
        线程主体方法;
    }
}

多线程启动的唯一方法是Thread类中的 public void start()方法

MyThread t = new MyThread();
t.start();

缺点:单继承问题

2.Runnable接口

@FunctionalInterface
public interface Runnable {//接口定义
    public void run() ;
}
class 类名 implements Runnable{
    属性;
    方法;
    @Override
    public void run(){//覆写run()方法
       ...
    }
}

启动方法:

MyThread t = new MyThread();
new Thread(t).start();

缺点:run()方法不能返回操作结果 

Thread类实现了Runnable接口

3.进程的生命周期

4.停止线程运行

class 类名 implements Runnable{
    属性;
    private boolean flag=true;
    方法;
    @Override
    public void run(){//覆写run()方法
        while(this.flag){
            ...
        }
    }
    public void stop(){
        this.flag=false;
    }
}
MyThread t = new MyThread();
new Thread(t).start();
t.stop();

5.休眠

try {
    Thread.sleep(1000); // 每次执行休眠1秒
} catch (InterruptedException e) {
    e.printStackTrace();
}

6.Callable接口

解决Runnable接口run()方法不能返回操作结果的问题

@FunctionalInterface
public interface Callable<V> {//接口定义
    public V call() throws Exception ;
}
import java.util.concurrent.Callable;
class MyThread implements Callable<String> {// 多线程主体类
    private int ticket = 10; // 卖票
    @Override
    public String call() throws Exception {
        for (int x = 0; x < 100; x++) {
            if (this.ticket > 0) {// 还有票可以出售
                System.out.println("卖票,ticket = " + 
                this.ticket--);
            } 
        }
    return "票已卖光!"; // 返回结果
    } 
}

启动方法:

public class TestDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt1 = new MyThread();// 实例化多线程对象
        MyThread mt2 = new MyThread();// 实例化多线程对象

        FutureTask<String> task1 = new FutureTask<String>(mt1) ;
        FutureTask<String> task2 = new FutureTask<String>(mt2) ;

        // FutureTask是Runnable接口子类,所以可以使用Thread类的构造来接收task对象
        new Thread(task1).start(); // 启动第一个线程
        new Thread(task2).start(); // 启动第二个线程

        // 多线程执行完毕后可以取得内容,依靠FutureTask的父接口Future中的get()方法实现
        System.out.println("A线程的返回结果:" + task1.get());
        System.out.println("B线程的返回结果:" + task2.get());
    } 
}

7.同步

一个代码块中的多个操作在同一个时间段内只能有一个线程进行,其他线程要等待此线程完成后才可以继续执行

实现同步方法:synchronized包装代码块/定义方法

class MyThread implements Runnable {
    private int ticket = 5; // 一共有5张票
    @Override
    public void run() {
        for (int x = 0; x < 20; x++) {
            synchronized(this) { // 定义同步代码块
                if (this.ticket > 0) { // 判断当前是否还有剩余票
                    try {
                        Thread.sleep(100); // 休眠1秒,模拟延迟
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()
                    + " 卖票,ticket = " + this.ticket);
                } 
            } 
        } 
    } 
}
class MyThread implements Runnable {
    private int ticket = 5; // 一共有5张票
    @Override
    public void run() {
        for (int x = 0; x < 20; x++) {
            this.sale(); // 卖票操作
        } 
    }
    public synchronized void sale() { // 同步方法
        if (this.ticket > 0) { // 判断当前是否还有剩余票
            try {
                Thread.sleep(100); // 休眠1秒,模拟延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ " 卖票,ticket = " + 
                    this.ticket--);
        }
    }
 }

8.线程的强制执行/礼让/优先级

线程强制执行完毕
public final void join() throws InterruptedException

线程强制执行若干毫秒
public final void join(long millis)throws InterruptedException

线程强制执行若干毫秒以及纳秒
public final void join(long millis,int nanos)throws InterruptedException

礼让
public static void yield()

设置优先级
public final void setPriority(int newPriority)

获取优先级
public final int getPriority()

最低优先级(数值为“10”)
public static final int MIN_PRIORITY

中等优先级(数值为“5”)
public static final int NORM_PRIORITY

最高优先级(数值为“1”)
public static final int MAX_PRIORITY

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值