多线程基础

重排序对多线程的总结

package ReorderExample;

public class RecordExample {
    int a = 0;
    boolean flag = false;

    public void write() {
        a = 1;  //1
        flag = true;  //2
    }

    public void reader() {
        if(flag) {   //3
            int i = a*a;   //4
        }
    }
}

上述flag是一个标记,标记a是否被写入。假设有两个线程A和·B,A首先执行write()方法,B首先执行read()方法,则B能否读取i = 1的值吗?
答案:不一定
因为操作1和操作2没有数据依赖关系,编译器和处理器可以对这两个操作重排序;同时操作3和操作4没有数据依赖关系,也可以进行重排序。程序执行时,执行顺序可以改为2 3 4 1, 则读出i的值是0.

线程的状态

这里写图片描述

Thread类也是实现Runnable接口
Runnable接口的实现

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

线程的创建

方式一:传递给一个target,调用target的run()方法
方式二:继承Thread类,重写run()方法。

线程的中断

public void Thread.interrupt()  中断线程
public boolena Thread.isInterrupt() 判断是否被中断
public static boolean Thread.interrupted; 判断是否被中断

中断线程的方法

public void run(){
    while(true){
        if(Thread.currentThread().isInterrupted()){
            break;
        }
        //做一些事情
    }
}

线程方法

  • yield()

    public static native void yield(); //谦让线程

  • join():等待线程结束

    public final void join() throws InterruptException

public class JoinMain{
    public static int i = 0;
    public static class AddressThread extends Thread{
        public void run(){
            for(int i = 0; i < 100000; i++){
                //输出i
            }
        }
    }
 public static void main(String[] args){
        AddThread at = new AddThread();
        at.start();
        at.join();
        Syso(i);
    }
}

join()方法的实质:

while(isAlive()){
    wait(0);
}

守护线程

在后台默默完成一些系统性的服务时候,是守护线程
当一个Java应用内,只有守护线程时候,Java虚拟机自然退出。

Thread t = new DaemonT();
t.setDaemon(true); //设置成为守护线程,必须在start之前
t.start();

线程优先级

设置线程优先级

high.setPriority(Thread.MAX_PRIORITY);

基本线程同步

synchronized关键字

指定加锁对象:给指定对象加锁,进入代码块前要获得给定对象的锁。
直接作用于实例方法:相当于对当前实例加锁,进入代码块前要获得当前实例的锁。
直接作用于静态方法:相当于对当前类加锁,进入同步代码块前要获得当前类的锁。

object.wait()

必须获得当前对象的监视器,拿到对象的锁,就是写在synchronized中。
释放当前的锁

object.nofity()

必须获取监视器,使得wait()线程可以进行争取线程。这是唤醒随机一个线程。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值