菜鸟笔记
提升您的技术认知

java多线程(超详细!)-ag真人游戏

进程是:一个应用程序(1个进程是一个软件)。

线程是:一个进程中的执行场景/执行单元。

注意:一个进程可以启动多个线程。

eg.
对于java程序来说,当在dos命令窗口中输入:
java helloworld 回车之后。会先启动jvm,而jvm就是一个进程

jvm再启动一个主线程调用main方法(main方法就是主线程)。
同时再启动一个垃圾回收线程负责看护,回收垃圾。

最起码,现在的java程序中至少有两个线程并发,一个是 垃圾回收线程,一个是 执行main方法的主线程

进程:可以看做是现实生活当中的公司。

线程:可以看做是公司当中的某个员工。

注意:
进程a和进程b的 内存独立不共享

eg.
魔兽游戏是一个进程
酷狗音乐是一个进程
这两个进程是独立的,不共享资源。

线程a和线程b是什么关系?

在java语言中:

线程a和线程b,堆内存方法区 内存共享。但是 栈内存 独立一个线程一个栈

eg.
假设启动10个线程,会有10个栈空间,每个栈和每个栈之间,互不干扰,各自执行各自的,这就是多线程并发。

eg.
火车站,可以看做是一个进程
火车站中的每一个售票窗口可以看做是一个线程
我在窗口1购票,你可以在窗口2购票,你不需要等我,我也不需要等你。所以多线程并发可以提高效率。

java中之所以有多线程机制,目的就是为了 提高程序的处理效率

使用了多线程机制之后,main方法结束,是不是有可能程序也不会结束?

main方法结束只是主线程结束了,主栈空了,其它的栈(线程)可能还在压栈弹栈。

4.分析一个问题

对于单核的cpu来说,真的可以做到真正的多线程并发吗?

对于多核的cpu电脑来说,真正的多线程并发是没问题的。4核cpu表示同一个时间点上,可以真正的有4个进程并发执行。

单核的cpu表示只有一个大脑:
不能够做到真正的多线程并发,但是可以做到给人一种“多线程并发”的感觉。

对于单核的cpu来说,在某一个时间点上实际上只能处理一件事情,但是由于cpu的处理速度极快,多个线程之间频繁切换执行,给别人的感觉是:多个事情同时在做!!!

eg.
线程a:播放音乐

线程b:运行魔兽游戏

线程a和线程b频繁切换执行,人类会感觉音乐一直在播放,游戏一直在运行,
给我们的感觉是同时并发的。(因为计算机的速度很快,我们人的眼睛很慢,所以才会感觉是多线程!)

t1线程执行t1的。
t2线程执行t2的。
t1不会影响t2,t2也不会影响t1。这叫做真正的多线程并发。

  1. 新建状态
  2. 就绪状态
  3. 运行状态
  4. 阻塞状态
  5. 死亡状态
构造方法名 备注
thread()
thread(string name) name为线程名字
创建线程第二种方式
thread(runnable target)
thread(runnable target, string name) name为线程名字

第一种方式:

编写一个类,直接 继承 java.lang.thread重写 run方法

  1. 怎么创建线程对象? new继承线程的类。
  2. 怎么启动线程呢? 调用线程对象的 start() 方法。

伪代码:

// 定义线程类
public class mythread extends thread{
  
	public void run(){
  
	
	}
}
// 创建线程对象
mythread t = new mythread();
// 启动线程。
t.start();

eg.

public class threadtest02 {
  
    public static void main(string[] args) {
  
        mythread t = new mythread();
        // 启动线程
        //t.run(); // 不会启动线程,不会分配新的分支栈。(这种方式就是单线程。)
        t.start();
        // 这里的代码还是运行在主线程中。
        for(int i = 0; i < 1000; i  ){
  
            system.out.println("主线程--->"   i);
        }
    }
}
class mythread extends thread {
  
    @override
    public void run() {
  
        // 编写程序,这段程序运行在分支线程中(分支栈)。
        for(int i = 0; i < 1000; i  ){
  
            system.out.println("分支线程--->"   i);
        }
    }
}

注意:

  • t.run() 不会启动线程,只是普通的调用方法而已。不会分配新的分支栈。(这种方式就是单线程。)

  • t.start() 方法的作用是:启动一个分支线程,在jvm中开辟一个新的栈空间,这段代码任务完成之后,瞬间就结束了。
    这段代码的任务只是为了开启一个新的栈空间,只要新的栈空间开出来,start()方法就结束了。线程就启动成功了。
    启动成功的线程会自动调用run方法,并且run方法在分支栈的栈底部(压栈)。
    run方法在分支栈的栈底部,main方法在主栈的栈底部。run和main是平级的。

调用run()方法内存图:

调用start()方法内存图:

第二种方式:

编写一个类,实现 java.lang.runnable 接口,实现run方法

  1. 怎么创建线程对象? new线程类传入可运行的类/接口。
  2. 怎么启动线程呢? 调用线程对象的 start() 方法。

伪代码:

// 定义一个可运行的类
public class myrunnable implements runnable {
  
	public void run(){
  
	
	}
}
// 创建线程对象
thread t = new thread(new myrunnable());
// 启动线程
t.start();

eg.

public class threadtest03 {
  
    public static void main(string[] args) {
  
        thread t = new thread(new myrunnable()); 
        // 启动线程
        t.start();
        
        for(int i = 0; i < 100; i  ){
  
            system.out.println("主线程--->"   i);
        }
    }
}
// 这并不是一个线程类,是一个可运行的类。它还不是一个线程。
class myrunnable implements runnable {
  
    @override
    public void run() {
  
        for(int i = 0; i < 100; i  ){
  
            system.out.println("分支线程--->"   i);
        }
    }
}

采用匿名内部类创建:

public class threadtest04 {
  
    public static void main(string[] args) {
  
        // 创建线程对象,采用匿名内部类方式。
        thread t = new thread(new runnable(){
  
            @override
            public void run() {
  
                for(int i = 0; i < 100; i  ){
  
                    system.out.println("t线程---> "   i);
                }
            }
        });
        // 启动线程
        t.start();
        for(int i = 0; i < 100; i  ){
  
            system.out.println("main线程---> "   i);
        }
    }
}

注意:
第二种方式实现接口比较常用,因为一个类实现了接口,它还可以去继承其它的类,更灵活。

方法名 作用
static thread currentthread() 获取当前线程对象
string getname() 获取线程对象名字
void setname(string name) 修改线程对象名字

当线程没有设置名字的时候,默认的名字是什么?

  • thread-0
  • thread-1
  • thread-2
  • thread-3

eg.

class mythread2 extends thread {
  
    public void run(){
  
        for(int i = 0; i < 100; i  ){
  
            // currentthread就是当前线程对象。当前线程是谁呢?
            // 当t1线程执行run方法,那么这个当前线程就是t1
            // 当t2线程执行run方法,那么这个当前线程就是t2
            thread currentthread = thread.currentthread();
            system.out.println(currentthread.getname()   "-->"   i);
            //system.out.println(super.getname()   "-->"   i);
            //system.out.println(this.getname()   "-->"   i);
        }
    }
}
方法名 作用
static void sleep(long millis) 让当前线程休眠millis秒
  1. 静态方法:thread.sleep(1000);
  2. 参数是毫秒
  3. 作用: 让当前线程进入休眠,进入“阻塞状态”,放弃占有cpu时间片,让给其它线程使用。
    这行代码出现在a线程中,a线程就会进入休眠。
    这行代码出现在b线程中,b线程就会进入休眠。
  4. thread.sleep()方法,可以做到这种效果:
    间隔特定的时间,去执行一段特定的代码,每隔多久执行一次。

eg.

public class threadtest06 {
  
    public static void main(string[] args) {
  
    	//每打印一个数字睡1s
        for(int i = 0; i < 10; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
            // 睡眠1秒
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}
方法名 作用
void interrupt() 终止线程的睡眠

eg.

public class threadtest08 {
  
    public static void main(string[] args) {
  
        thread t = new thread(new myrunnable2());
        t.setname("t");
        t.start();
        // 希望5秒之后,t线程醒来(5秒之后主线程手里的活儿干完了。)
        try {
  
            thread.sleep(1000 * 5);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        // 终断t线程的睡眠(这种终断睡眠的方式依靠了java的异常处理机制。)
        t.interrupt();
    }
}
class myrunnable2 implements runnable {
  
    @override
    public void run() {
  
        system.out.println(thread.currentthread().getname()   "---> begin");
        try {
  
            // 睡眠1年
            thread.sleep(1000 * 60 * 60 * 24 * 365);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        //1年之后才会执行这里
        system.out.println(thread.currentthread().getname()   "---> end");
}

为什么run()方法只能try…catch…不能throws?

因为run()方法在父类中没有抛出任何异常子类不能比父类抛出更多的异常

eg.

public class threadtest09 {
  
    public static void main(string[] args) {
  
        thread t = new thread(new myrunnable3());
        t.setname("t");
        t.start();
        // 模拟5秒
        try {
  
            thread.sleep(1000 * 5);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        // 5秒之后强行终止t线程
        t.stop(); // 已过时(不建议使用。)
    }
}
class myrunnable3 implements runnable {
  
    @override
    public void run() {
  
        for(int i = 0; i < 10; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}

注意:

这种方式存在很大的缺点:容易丢失数据

因为这种方式是直接将线程杀死了,线程没有保存的数据将会丢失。不建议使用。

eg.

public class threadtest10 {
  
    public static void main(string[] args) {
  
        myrunable4 r = new myrunable4();
        thread t = new thread(r);
        t.setname("t");
        t.start();
        // 模拟5秒
        try {
  
            thread.sleep(5000);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        // 终止线程
        // 你想要什么时候终止t的执行,那么你把标记修改为false,就结束了。
        r.run = false;
    }
}
class myrunable4 implements runnable {
  
    // 打一个布尔标记
    boolean run = true;
    @override
    public void run() {
  
        for (int i = 0; i < 10; i  ){
  
            if(run){
  
                system.out.println(thread.currentthread().getname()   "--->"   i);
                try {
  
                    thread.sleep(1000);
                } catch (interruptedexception e) {
  
                    e.printstacktrace();
                }
            }else{
  
                // return就结束了,你在结束之前还有什么没保存的。
                // 在这里可以保存呀。
                //save....
                //终止当前线程
                return;
            }
        }
    }
}

为什么if()语句要在循环里面?

由于一个线程一直运行此程序,要是if判断在外面只会在启动线程时判断并不会结束,因此需要每次循环判断一下标记。

1.常见的线程调度模型有哪些?

  • 抢占式调度模型:
    那个线程的优先级比较高,抢到的cpu时间片的概率就高一些/多一些。
    java采用的就是抢占式调度模型

  • 均分式调度模型:
    平均分配cpu时间片。每个线程占有的cpu时间片时间长度一样。
    平均分配,一切平等。
    有一些编程语言,线程调度模型采用的是这种方式。

2.java中提供了哪些方法是和线程调度有关系的呢?

2.1实例方法:

方法名 作用
int getpriority() 获得线程优先级
void setpriority(int newpriority) 设置线程优先级
  • 最低优先级1
  • 默认优先级是5
  • 最高优先级10

优先级比较高的获取cpu时间片可能会多一些。(但也不完全是,大概率是多的。)

2.2静态方法:

方法名 作用
static void yield() 让位方法,当前线程暂停,回到就绪状态,让给其它线程。

yield()方法不是阻塞方法。让当前线程让位,让给其它线程使用。

yield()方法的执行会让当前线程从“运行状态”回到“就绪状态”。

注意:在回到就绪之后,有可能还会再次抢到

2.3实例方法:

方法名 作用
void join() 将一个线程合并到当前线程中,当前线程受阻塞,加入的线程执行直到结束

eg.

class mythread1 extends thread {
  
	public void dosome(){
  
		mythread2 t = new mythread2();
		t.join(); // 当前线程进入阻塞,t线程执行,直到t线程结束。当前线程才可以继续。
	}
}
class mythread2 extends thread{
  
}

常量:

常量名 备注
static int max_priority 最高优先级(10)
static int min_priority 最低优先级(1)
static int norm_priority 默认优先级(5)

方法:

方法名 作用
int getpriority() 获得线程优先级
void setpriority(int newpriority) 设置线程优先级
public class threadtest11 {
  
    public static void main(string[] args) {
  
        system.out.println("最高优先级:"   thread.max_priority);//最高优先级:10
        system.out.println("最低优先级:"   thread.min_priority);//最低优先级:1
        system.out.println("默认优先级:"   thread.norm_priority);//默认优先级:5
        
        // main线程的默认优先级是:5
        system.out.println(hread.currentthread().getname()   "线程的默认优先级是:"   currentthread.getpriority());
        thread t = new thread(new myrunnable5());
        t.setpriority(10);
        t.setname("t");
        t.start();
        // 优先级较高的,只是抢到的cpu时间片相对多一些。
        // 大概率方向更偏向于优先级比较高的。
        for(int i = 0; i < 10000; i  ){
  
            system.out.println(thread.currentthread().getname()   "-->"   i);
        }
    }
}
class myrunnable5 implements runnable {
  
    @override
    public void run() {
  
        for(int i = 0; i < 10000; i  ){
  
            system.out.println(thread.currentthread().getname()   "-->"   i);
        }
    }
}

注意:

  • main线程的默认优先级是:5
  • 优先级较高的,只是抢到的cpu时间片相对多一些。大概率方向更偏向于优先级比较高的。
方法名 作用
static void yield() 让位,当前线程暂停,回到就绪状态,让给其它线程。

eg.

public class threadtest12 {
  
    public static void main(string[] args) {
  
        thread t = new thread(new myrunnable6());
        t.setname("t");
        t.start();
        for(int i = 1; i <= 10000; i  ) {
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
class myrunnable6 implements runnable {
  
    @override
    public void run() {
  
        for(int i = 1; i <= 10000; i  ) {
  
            //每100个让位一次。
            if(i % 100 == 0){
  
                thread.yield(); // 当前线程暂停一下,让给主线程。
            }
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}

注意: 并不是每次都让成功的,有可能它又抢到时间片了。

方法名 作用
void join() 将一个线程合并到当前线程中,当前线程受阻塞,加入的线程执行直到结束
void join(long millis) 接上条,等待该线程终止的时间最长为 millis 毫秒
void join(long millis, int nanos) 接第一条,等待该线程终止的时间最长为 millis 毫秒 nanos 纳秒

eg.

public class threadtest13 {
  
    public static void main(string[] args) {
  
        system.out.println("main begin");
        thread t = new thread(new myrunnable7());
        t.setname("t");
        t.start();
        //合并线程
        try {
  
            t.join(); // t合并到当前线程中,当前线程受阻塞,t线程执行直到结束。
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        system.out.println("main over");
    }
}
class myrunnable7 implements runnable {
  
    @override
    public void run() {
  
        for(int i = 0; i < 10000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}

注意: 一个线程.join(),当前线程会进入”阻塞状态“。等待加入线程执行完!

1.为什么这个是重点?

以后在开发中,我们的项目都是运行在服务器当中,而服务器已经将线程的定义,线程对象的创建,线程的启动等,都已经实现完了。这些代码我们都不需要编写。

最重要的是: 你要知道,你编写的程序需要放到一个多线程的环境下运行,你更需要关注的是这些数据在多线程并发的环境下是否是安全的。(重点:

2.什么时候数据在多线程并发的环境下会存在安全问题呢?

满足三个条件:

  1. 条件1:多线程并发
  2. 条件2:有共享数据
  3. 条件3:共享数据有修改的行为

满足以上3个条件之后,就会存在线程安全问题。

3.怎么解决线程安全问题呢?

多线程并发的环境下,有共享数据,并且这个数据还会被修改,此时就存在线程安全问题,怎么解决这个问题?

线程排队执行。(不能并发)。用排队执行解决线程安全问题。

这种机制被称为:线程同步机制

专业术语叫做线程同步,实际上就是线程不能并发了,线程必须排队执行。

线程同步就是线程排队了,线程排队了就会 牺牲一部分效率 ,没办法,数据安全第一位,只有数据安全了,我们才可以谈效率。数据不安全,没有效率的事儿。

4.两个专业术语:

异步编程模型:
线程t1和线程t2,各自执行各自的,t1不管t2,t2不管t1,谁也不需要等谁,这种编程模型叫做:异步编程模型。

其实就是:多线程并发(效率较高。)

异步就是并发。

同步编程模型:
线程t1和线程t2,在线程t1执行的时候,必须等待t2线程执行结束,或者说在t2线程执行的时候,必须等待t1线程执行结束,两个线程之间发生了等待关系,这就是同步编程模型。

效率较低。线程排队执行。

同步就是排队。

16.1synchronized-线程同步

线程同步机制的语法是:

synchronized(){
  
	// 线程同步代码块。
}

重点:
synchronized后面小括号() 中传的这个“数据”是相当关键的。这个数据必须是 多线程共享 的数据。才能达到多线程排队。

16.1.1 ()中写什么?

那要看你想让哪些线程同步。

假设t1、t2、t3、t4、t5,有5个线程,你只希望t1 t2 t3排队,t4 t5不需要排队。怎么办?

你一定要在()中写一个t1 t2 t3共享的对象。而这个对象对于t4 t5来说不是共享的。

这里的共享对象是:账户对象。
账户对象是共享的,那么this就是账户对象!!!
()不一定是this,这里只要是多线程共享的那个对象就行。

注意:
在java语言中,任何一个对象都有“一把锁”,其实这把锁就是标记。(只是把它叫做锁。)
100个对象,100把锁。1个对象1把锁。

16.1.2 以下代码的执行原理?(

1、假设t1和t2线程并发,开始执行以下代码的时候,肯定有一个先一个后。

2、假设t1先执行了,遇到了synchronized,这个时候自动找“后面共享对象”的对象锁
找到之后,并占有这把锁,然后执行同步代码块中的程序,在程序执行过程中一直都是
占有这把锁的。直到同步代码块代码结束,这把锁才会释放。

3、假设t1已经占有这把锁,此时t2也遇到synchronized关键字,也会去占有后面
共享对象的这把锁,结果这把锁被t1占有,t2只能在同步代码块外面等待t1的结束
直到t1把同步代码块执行结束了,t1会归还这把锁,此时t2终于等到这把锁,然后
t2占有这把锁之后,进入同步代码块执行程序。

4、这样就达到了线程排队执行。

重中之重:
这个共享对象一定要选好了。这个共享对象一定是你需要排队
执行的这些线程对象所共享的。

class account {
  
    private string actno;
    private double balance; //实例变量。
    //对象
    object o= new object(); // 实例变量。(account对象是多线程共享的,account对象中的实例变量obj也是共享的。)
    public account() {
  
    }
    public account(string actno, double balance) {
  
        this.actno = actno;
        this.balance = balance;
    }
    public string getactno() {
  
        return actno;
    }
    public void setactno(string actno) {
  
        this.actno = actno;
    }
    public double getbalance() {
  
        return balance;
    }
    public void setbalance(double balance) {
  
        this.balance = balance;
    }
    //取款的方法
    public void withdraw(double money){
  
        /**
         * 以下可以共享,金额不会出错
         * 以下这几行代码必须是线程排队的,不能并发。
         * 一个线程把这里的代码全部执行结束之后,另一个线程才能进来。
         */
        synchronized(this) {
  
        //synchronized(actno) {
  
        //synchronized(o) {
  
        
        /**
         * 以下不共享,金额会出错
         */
		  /*object obj = new object();
	        synchronized(obj) { // 这样编写就不安全了。因为obj2不是共享对象。
	        synchronized(null) {//编译不通过
	        string s = null;
	        synchronized(s) {//java.lang.nullpointerexception*/
            double before = this.getbalance();
            double after = before - money;
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
            this.setbalance(after);
        //}
    }
}
class accountthread extends thread {
  
    // 两个线程必须共享同一个账户对象。
    private account act;
    // 通过构造方法传递过来账户对象
    public accountthread(account act) {
  
        this.act = act;
    }
    public void run(){
  
        double money = 5000;
        act.withdraw(money);
        system.out.println(thread.currentthread().getname()   "对" act.getactno() "取款" money "成功,余额"   act.getbalance());
    }
}
public class test {
  
    public static void main(string[] args) {
  
        // 创建账户对象(只创建1个)
        account act = new account("act-001", 10000);
        // 创建两个线程,共享同一个对象
        thread t1 = new accountthread(act);
        thread t2 = new accountthread(act);
        t1.setname("t1");
        t2.setname("t2");
        t1.start();
        t2.start();
    }
}

以上代码锁this、实例变量actno、实例变量o都可以!因为这三个是线程共享!

16.1.3 在实例方法上可以使用synchronized

synchronized出现在实例方法上,一定锁的是 this

没得挑。只能是this。不能是其他的对象了。所以这种方式不灵活

16.1.3.1 缺点

synchronized出现在实例方法上,表示整个方法体都需要同步,可能会无故扩大同步的范围,导致程序的执行效率降低。所以这种方式不常用

16.1.3.2 优点

代码写的少了。节俭了。

16.1.3.3 总结

如果共享的对象就是this,并且需要同步的代码块是整个方法体,建议使用这种方式。、

eg.

    public synchronized void withdraw(double money){
  
        double before = this.getbalance();
        double after = before - money;
        try {
  
            thread.sleep(1000);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        this.setbalance(after);
    }

16.1.4 在方法调用处使用synchronized

eg.

    public void run(){
  
        double money = 5000;
        // 取款
        // 多线程并发执行这个方法。
        //synchronized (this) { //这里的this是accountthread对象,这个对象不共享!
        synchronized (act) {
   // 这种方式也可以,只不过扩大了同步的范围,效率更低了。
            act.withdraw(money);
        }
        system.out.println(thread.currentthread().getname()   "对" act.getactno() "取款" money "成功,余额"   act.getbalance());
    }

这种方式也可以,只不过扩大了同步的范围,效率更低了。

  • 实例变量:在中。
  • 静态变量:在方法区
  • 局部变量:在中。

以上三大变量中:

局部变量永远都不会存在线程安全问题。

  • 因为局部变量不共享。(一个线程一个栈。)
  • 局部变量在中。所以局部变量永远都不会共享。
  1. 实例变量在堆中,堆只有1个。
  2. 静态变量在方法区中,方法区只有1个。

堆和方法区都是多线程共享的,所以可能存在线程安全问题。

总结:

  • 局部变量 常量:不会有线程安全问题。
  • 成员变量(实例 静态):可能会有线程安全问题。

如果使用局部变量的话:

建议使用:stringbuilder

因为局部变量不存在线程安全问题。选择stringbuilder。

stringbuffer效率比较低。

反之:

使用stringbuffer。

  • arraylist是非线程安全的。
  • vector是线程安全的。
  • hashmap hashset是非线程安全的。
  • hashtable是线程安全的。

synchronized有三种写法:

第一种:同步代码块

灵活

synchronized(线程共享对象){
  
	同步代码块;
}

第二种:在实例方法上使用synchronized

表示共享对象一定是 this 并且同步代码块是整个方法体

第三种:在静态方法上使用synchronized

表示找 类锁类锁永远只有1把

就算创建了100个对象,那类锁也只有1把。

注意区分:

  • 对象锁:1个对象1把锁,100个对象100把锁。
  • 类锁:100个对象,也可能只是1把类锁。

是一上来就选择线程同步吗?synchronized

不是,synchronized会让程序的执行效率降低,用户体验不好。
系统的用户吞吐量降低。用户体验差。在不得已的情况下再选择线程同步机制。

  • 第一种方案:尽量使用局部变量 代替实例变量静态变量”。

  • 第二种方案:如果必须是实例变量,那么可以考虑创建多个对象,这样实例变量的内存就不共享了。(一个线程对应1个对象,100个线程对应100个对象,对象不共享,就没有数据安全问题了。)

  • 第三种方案:如果不能使用局部变量,对象也不能创建多个,这个时候就只能选择synchronized了。线程同步机制

死锁代码要会写。一般面试官要求你会写。
只有会写的,才会在以后的开发中注意这个事儿。
因为死锁很难调试。

/**
 * 比如:t1想先穿衣服在穿裤子
 *       t2想先穿裤子在传衣服
 * 此时:t1拿到衣服,t2拿到裤子;
 * 由于t1拿了衣服,t2找不到衣服;t2拿了裤子,t1找不到裤子
 * 就会导致死锁的发生!
 */
public class thread_deadlock {
  
    public static void main(string[] args) {
  
        dress dress = new dress();
        trousers trousers = new trousers();
        //t1、t2共享dress和trousers。
        thread t1 = new thread(new myrunnable1(dress, trousers), "t1");
        thread t2 = new thread(new myrunnable2(dress, trousers), "t2");
        t1.start();
        t2.start();
    }
}
class myrunnable1 implements runnable{
  
    dress dress;
    trousers trousers;
    public myrunnable1() {
  
    }
    public myrunnable1(dress dress, trousers trousers) {
  
        this.dress = dress;
        this.trousers = trousers;
    }
    @override
    public void run() {
  
        synchronized(dress){
  
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
            synchronized (trousers){
  
                system.out.println("--------------");
            }
        }
    }
}
class myrunnable2 implements runnable{
  
    dress dress;
    trousers trousers;
    public myrunnable2() {
  
    }
    public myrunnable2(dress dress, trousers trousers) {
  
        this.dress = dress;
        this.trousers = trousers;
    }
    @override
    public void run() {
  
        synchronized(trousers){
  
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
            synchronized (dress){
  
                system.out.println("。。。。。。。。。。。。。。");
            }
        }
    }
}
class dress{
  
}
class trousers{
  
}

22.1java语言中线程分为两大类:

  • 一类是:用户线程
  • 一类是:守护线程后台线程

其中具有代表性的就是:垃圾回收线程(守护线程)

22.2守护线程的特点:

一般守护线程是一个死循环所有的用户线程只要结束,守护线程自动结束

注意:主线程main方法是一个用户线程。

22.3守护线程用在什么地方呢?

每天00:00的时候系统数据自动备份。
这个需要使用到定时器,并且我们可以将定时器设置为守护线程。
一直在那里看着,没到00:00的时候就备份一次。所有的用户线程如果结束了,守护线程自动退出,没有必要进行数据备份了。

22.4方法

方法名 作用
void setdaemon(boolean on) on为true表示把线程设置为守护线程

eg.

public class threadtest14 {
  
    public static void main(string[] args) {
  
        thread t = new bakdatathread();
        t.setname("备份数据的线程");
        // 启动线程之前,将线程设置为守护线程
        t.setdaemon(true);
        t.start();
        // 主线程:主线程是用户线程
        for(int i = 0; i < 10; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}
class bakdatathread extends thread {
  
    public void run(){
  
        int i = 0;
        // 即使是死循环,但由于该线程是守护者,当用户线程结束,守护线程自动终止。
        while(true){
  
            system.out.println(thread.currentthread().getname()   "--->"   (  i));
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}

23.1定时器的作用:

间隔特定的时间,执行特定的程序。

eg.
每周要进行银行账户的总账操作。
每天要进行数据的备份操作。

在实际的开发中,每隔多久执行一段特定的程序,这种需求是很常见的,那么在java中其实可以采用多种方式实现:

  1. 可以使用sleep方法,睡眠,设置睡眠时间,没到这个时间点醒来,执行任务。这种方式是最原始的定时器。(比较low)

  2. 在java的类库中已经写好了一个定时器:java.util.timer,可以直接拿来用。
    不过,这种方式在目前的开发中也很少用,因为现在有很多高级框架都是支持定时任务的。

在实际的开发中,目前使用较多的是spring框架中提供的springtask框架,这个框架只要进行简单的配置,就可以完成定时器的任务。

构造方法

构造方法名 备注
timer() 创建一个定时器
timer(boolean isdaemon) isdaemon为true为守护线程定时器
timer(string name) 创建一个定时器,其线程名字为name
timer(string name, boolean isdaemon) 结合2、3

方法

方法名 作用
void schedule(timertask task, date firsttime, long period) 安排指定的任务在指定的时间开始进行重复的固定延迟执行
void cancel() 终止定时器

正常方式:

class timertest01{
  
    public static void main(string[] args) {
  
        timer timer = new timer();
//        timer timer = new timer(true);//守护线程
        string firsttimestr = "2021-05-09 17:27:00";
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        try {
  
            date firsttime = sdf.parse(firsttimestr);
            timer.schedule(new mytimertask(), firsttime, 1000 * 5);//每5s执行一次
        } catch (parseexception e) {
  
            e.printstacktrace();
        }
    }
}
class mytimertask extends timertask{
  
    @override
    public void run() {
  
        date d = new date();
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        string time = sdf.format(d);
        system.out.println(time   ":备份日志一次!");
    }
}

匿名内部类方式:

class timertest02{
  
    public static void main(string[] args) {
  
        timer timer = new timer();
        string firsttimestr = "2021-05-09 17:56:00";
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        try {
  
            date firsttime = sdf.parse(firsttimestr);
            timer.schedule(new timertask() {
  
                @override
                public void run() {
  
                    date d = new date();
                    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
                    string time = sdf.format(d);
                    system.out.println(time   ":备份日志一次!");
                }
            }, firsttime, 1000 * 5);
        } catch (parseexception e) {
  
            e.printstacktrace();
        }
    }
}

这种方式实现的线程可以获取线程的返回值

之前讲解的那两种方式是无法获取线程返回值的,因为run方法返回void

任务需求:
系统委派一个线程去执行一个任务,该线程执行完任务之后,可能会有一个执行结果,我们怎么能拿到这个执行结果呢?
使用第三种方式:实现callable接口方式。

25.1优点

可以获取到线程的执行结果。

25.2缺点

效率比较低,在获取t线程执行结果的时候,当前线程受阻塞,效率较低。

eg.

public class threadtest15 {
  
    public static void main(string[] args) throws exception {
  
        // 第一步:创建一个“未来任务类”对象。
        // 参数非常重要,需要给一个callable接口实现类对象。
        futuretask task = new futuretask(new callable() {
  
            @override
            public object call() throws exception {
   // call()方法就相当于run方法。只不过这个有返回值
                // 线程执行一个任务,执行之后可能会有一个执行结果
                // 模拟执行
                system.out.println("call method begin");
                thread.sleep(1000 * 10);
                system.out.println("call method end!");
                int a = 100;
                int b = 200;
                return a   b; //自动装箱(300结果变成integer)
            }
        });
        // 创建线程对象
        thread t = new thread(task);
        // 启动线程
        t.start();
        // 这里是main方法,这是在主线程中。
        // 在主线程中,怎么获取t线程的返回结果?
        // get()方法的执行会导致“当前线程阻塞”
        object obj = task.get();
        system.out.println("线程执行结果:"   obj);
        // main方法这里的程序要想执行必须等待get()方法的结束
        // 而get()方法可能需要很久。因为get()方法是为了拿另一个线程的执行结果
        // 另一个线程执行是需要时间的。
        system.out.println("hello world!");
    }
}

26.1方法

方法名 作用
void wait() 让活动在当前对象的线程无限等待(释放之前占有的锁)
void notify() 唤醒当前对象正在等待的线程(只提示唤醒,不会释放锁)
void notifyall() 唤醒当前对象全部正在等待的线程(只提示唤醒,不会释放锁)

26.2方法详解

  1. 第一:wait和notify方法不是线程对象的方法,是java中任何一个java对象都有的方法,因为这两个方法是 object类中自带 的。

wait方法和notify方法不是通过线程对象调用
不是这样的:t.wait(),也不是这样的:t.notify()…不对。

  1. 第二wait()方法作用
object o = new object();
o.wait();

表示:
让正在o对象上活动的线程进入等待状态,无期限等待,直到被唤醒为止。

o.wait();方法的调用,会让“当前线程(正在o对象上活动的线程)”进入等待状态。

  1. 第三notify()方法作用
object o = new object();
o.notify();

表示:
唤醒正在o对象上等待的线程。

  1. 第四notifyall() 方法 作用
object o = new object();
o.notifyall();

表示:
这个方法是唤醒o对象上处于等待的所有线程

26.3图文

26.4总结 (呼应生产者消费者模式)

1、wait和notify方法不是线程对象的方法,是普通java对象都有的方法。

2、wait方法和notify方法建立在 线程同步 的基础之上。因为多线程要同时操作一个仓库。有线程安全问题。

3、wait方法作用:o.wait() 让正在o对象上活动的线程t进入等待状态,并且释放掉t线程之前占有的o对象的锁

4、notify方法作用:o.notify() 让正在o对象上等待的线程唤醒,只是通知,不会释放o对象上之前占有的锁

27.1什么是“生产者和消费者模式”?

  • 生产线程负责生产,消费线程负责消费。
  • 生产线程和消费线程要达到均衡。
  • 这是一种特殊的业务需求,在这种特殊的情况下需要使用wait方法和notify方法

27.2模拟一个业务需求

模拟这样一个需求:

  • 仓库我们采用list集合。

  • list集合中假设只能存储1个元素。

  • 1个元素就表示仓库了。

  • 如果list集合中元素个数是0,就表示仓库了。

  • 保证list集合中永远都是最多存储1个元素。

  • 必须做到这种效果:生产1个消费1个

27.3图文

eg.

使用wait方法和notify方法实现“生产者和消费者模式”

public class threadtest16 {
  
    public static void main(string[] args) {
  
        // 创建1个仓库对象,共享的。
        list list = new arraylist();
        // 创建两个线程对象
        // 生产者线程
        thread t1 = new thread(new producer(list));
        // 消费者线程
        thread t2 = new thread(new consumer(list));
        t1.setname("生产者线程");
        t2.setname("消费者线程");
        t1.start();
        t2.start();
    }
}
// 生产线程
class producer implements runnable {
  
    // 仓库
    private list list;
    public producer(list list) {
  
        this.list = list;
    }
    @override
    public void run() {
  
        // 一直生产(使用死循环来模拟一直生产)
        while(true){
  
            // 给仓库对象list加锁。
            synchronized (list){
  
                if(list.size() > 0){
   // 大于0,说明仓库中已经有1个元素了。
                    try {
  
                        // 当前线程进入等待状态,并且释放producer之前占有的list集合的锁。
                        list.wait();
                    } catch (interruptedexception e) {
  
                        e.printstacktrace();
                    }
                }
                // 程序能够执行到这里说明仓库是空的,可以生产
                object obj = new object();
                list.add(obj);
                system.out.println(thread.currentthread().getname()   "--->"   obj);
                // 唤醒消费者进行消费
                list.notifyall();
            }
        }
    }
}
// 消费线程
class consumer implements runnable {
  
    // 仓库
    private list list;
    public consumer(list list) {
  
        this.list = list;
    }
    @override
    public void run() {
  
        // 一直消费
        while(true){
  
            synchronized (list) {
  
                if(list.size() == 0){
  
                    try {
  
                        // 仓库已经空了。
                        // 消费者线程等待,释放掉list集合的锁
                        list.wait();
                    } catch (interruptedexception e) {
  
                        e.printstacktrace();
                    }
                }
                // 程序能够执行到此处说明仓库中有数据,进行消费。
                object obj = list.remove(0);
                system.out.println(thread.currentthread().getname()   "--->"   obj);
                // 唤醒生产者生产。
                list.notifyall();
            }
        }
    }
}

注意:
生产者消费者模式貌似只能使用wait()和notify()实现!

thread

package javase;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.*;
import java.util.concurrent.callable;
import java.util.concurrent.executionexception;
import java.util.concurrent.futuretask;
public class threadtest {
  
    public static void main(string[] args) {
  
    }
}
//创建线程的第一种方法:继承thread类
class threadtest01{
  
    public static void main(string[] args) {
  
        mythread01 t = new mythread01();
        t.setname("t");
        t.start();//启动线程
        for (int i = 0; i < 1000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
class mythread01 extends thread{
  
    @override
    public void run() {
  
        for (int i = 0; i < 1000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
//创建线程的第二种方法:实现runnable接口
class threadtest02{
  
    public static void main(string[] args) {
  
        thread t = new thread(new myrunnable01(), "t");//创建线程并设置名字
        t.start();
        for (int i = 0; i < 1000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
// 这并不是一个线程类,是一个可运行的类。它还不是一个线程。
class myrunnable01 implements runnable{
  
    @override
    public void run() {
  
        for (int i = 0; i < 1000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
//创建线程的第二种方法:实现runnable接口(采用匿名内部类)
class threadtest03{
  
    public static void main(string[] args) {
  
        //匿名内部类
        thread t = new thread(new runnable() {
  
            @override
            public void run() {
  
                for (int i = 0; i < 1000; i  ){
  
                    system.out.println(thread.currentthread().getname()   "--->"   i);
                }
            }
        });
        t.setname("t");
        t.start();
        for (int i = 0; i < 1000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
/**
 * thread.currentthread()获取当前线程对象(静态方法)
 * 线程.getname()获取当前线程名字
 * 线程.setname()设置当前线程名字
 */
class threadtest04{
  
    public static void main(string[] args) {
  
        system.out.println(thread.currentthread().getname());//当前线程名字 main
        mythread01 t1 = new mythread01();
        mythread01 t2 = new mythread01();
        t1.setname("t1");
        t2.setname("t2");
        t1.start();
        t2.start();
        for (int i = 0; i < 1000; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
//sleep(long millis)(静态方法)
class threadtest05{
  
    public static void main(string[] args) {
  
        for (int i = 0; i < 10; i  ){
  
            try {
  
                thread.sleep(1000);//睡眠1s
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
//interrupt()中断正在睡眠的线程(不推荐使用,了解即可)
class threadtest06 {
  
    public static void main(string[] args) {
  
        mythread02 t = new mythread02();
        t.setname("t");
        t.start();
        try {
  
            thread.sleep(1000 * 5);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        system.out.println("hello world");
        t.interrupt();
    }
}
class mythread02 extends thread{
  
    @override
    public void run() {
  
        system.out.println(thread.currentthread().getname()   "--->begin" );
        try {
  
            thread.sleep(1000 * 60 * 60 * 24 * 365);//睡一年
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        system.out.println(thread.currentthread().getname()   "--->end" );
    }
}
//stop()终止一个线程执行(不推荐使用,可能导致数据丢失)
class threadtest07{
  
    public static void main(string[] args) {
  
        mythread03 t = new mythread03();
        t.setname("t");
        t.start();
        try {
  
            thread.sleep(1000 * 5);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        t.stop();
    }
}
class mythread03 extends thread{
  
    @override
    public void run() {
  
        for (int i = 0; i < 100; i  ){
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}
//合理终止一个线程:设置一个标记
class threadtest08{
  
    public static void main(string[] args) {
  
        mythread04 t = new mythread04();
        t.setname("t");
        t.start();
        try {
  
            thread.sleep(1000 * 5);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        system.out.println("hello world");
        // 终止线程
        // 你想要什么时候终止t的执行,那么你把标记修改为false,就结束了。
        t.flag = true;
    }
}
class mythread04 extends thread{
  
    boolean flag = false;
    @override
    public void run() {
  
        if (this.flag){
  
            return ;
        }
        for (int i = 0; i < 1000; i  ){
  
            if (this.flag){
  //由于一个线程一直运行此程序,要是判断在外面只会在启动线程时判断并不会结束,因此需要每次循环判断一下标记。
                /**
                 * 这里可以保存东西
                 */
                return ;
            }
            system.out.println(thread.currentthread().getname()   "--->"   i);
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}
/*//mythread04另一种写法
class mythread04 extends thread{
    boolean flag = false;
    @override
    public void run() {
        for (int i = 0; i < 1000; i  ){
            if (!this.flag){
                system.out.println(thread.currentthread().getname()   "--->"   i);
                try {
                    thread.sleep(1000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }else{
                return;
            }
        }
    }
}*/
/**关于线程的优先级
 *getpriority()获得线程优先级
 *setpriority()设置线程优先级
 */
class threadtest09{
  
    public static void main(string[] args) {
  
        system.out.println("最高优先级:"   thread.max_priority);//最高优先级:10
        system.out.println("最低优先级:"   thread.min_priority);//最低优先级:1
        system.out.println("默认优先级:"   thread.norm_priority);//默认优先级:5
        mythread01 t1 = new mythread01();
        mythread01 t2 = new mythread01();
        mythread01 t3 = new mythread01();
        t1.setname("t1");
        t2.setname("t2");
        t3.setname("t3");
        t1.setpriority(thread.max_priority);
        t2.setpriority(thread.min_priority);
        t3.setpriority(thread.norm_priority);
        t1.start();
        t2.start();
        t3.start();
        try {
  
            thread.sleep(1000 * 5);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        system.out.println("t1的优先级:"   t1.getpriority());//t1的优先级:10
        system.out.println("t2的优先级:"   t2.getpriority());//t2的优先级:1
        system.out.println("t3的优先级:"   t3.getpriority());//t3的优先级:5
    }
}
//yield()让位,当前线程暂停,回到就绪状态,让给其它线程(静态方法)
class threadtest10{
  
    public static void main(string[] args) {
  
        thread t1 = new thread(new myrunnable02(), "t1");
        thread t2 = new thread(new myrunnable02(), "t2");
        t1.start();
        t2.start();
    }
}
class myrunnable02 implements runnable{
  
    @override
    public void run() {
  
        for (int i = 0; i < 1000; i  ){
  
            //每100个让位一次。
            if (i % 100 == 0){
  
                thread.yield();// 当前线程暂停一下,让给主线程。
            }
            system.out.println(thread.currentthread().getname()   "--->"   i);
        }
    }
}
//join()线程合并。将一个线程合并到当前线程中,当前线程受阻塞,加入的线程执行直到结束。
class threadtest11{
  
    public static void main(string[] args) {
  
        system.out.println("main begin");
        mythread01 t1 = new mythread01();
        t1.setname("t1");
        t1.start();
        try {
  
            t1.join();//t合并到当前线程中,当前线程受阻塞,t线程执行直到结束。
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        }
        system.out.println("main end");
    }
}
//守护线程
class threadtest12{
  
    public static void main(string[] args) {
  
        mythread05 t = new mythread05();
        t.setname("t");
        t.setdaemon(true);//设置守护线程
        t.start();
        for (int i = 0; i < 10; i  ) {
  
            system.out.println(thread.currentthread().getname()   "--->"   i);
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}
class mythread05 extends thread{
  
    @override
    public void run() {
  
        int i = 0;
        while (true){
  
            system.out.println(thread.currentthread().getname()   "--->"   i  );
            try {
  
                thread.sleep(1000);
            } catch (interruptedexception e) {
  
                e.printstacktrace();
            }
        }
    }
}
//使用定时器实现日志备份
class timertest01{
  
    public static void main(string[] args) {
  
        timer timer = new timer();
//        timer timer = new timer(true);//守护线程
        string firsttimestr = "2021-05-09 17:27:00";
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        try {
  
            date firsttime = sdf.parse(firsttimestr);
            timer.schedule(new mytimertask(), firsttime, 1000 * 5);//每5s执行一次
        } catch (parseexception e) {
  
            e.printstacktrace();
        }
    }
}
class mytimertask extends timertask{
  
    @override
    public void run() {
  
        date d = new date();
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        string time = sdf.format(d);
        system.out.println(time   ":备份日志一次!");
    }
}
class timertest02{
  
    public static void main(string[] args) {
  
        timer timer = new timer();
        string firsttimestr = "2021-05-09 17:56:00";
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        try {
  
            date firsttime = sdf.parse(firsttimestr);
            timer.schedule(new timertask() {
  
                @override
                public void run() {
  
                    date d = new date();
                    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
                    string time = sdf.format(d);
                    system.out.println(time   ":备份日志一次!");
                }
            }, firsttime, 1000 * 5);
        } catch (parseexception e) {
  
            e.printstacktrace();
        }
    }
}
//实现线程的第三种方式:实现callable接口
class threadtest13{
  
    public static void main(string[] args) {
  
        system.out.println("main begin");
        futuretask task = new futuretask(new mycallable());
        thread t = new thread(task, "t");
        t.start();
        try {
  
            object o = task.get();//会导致main线程阻塞
            system.out.println("task线程运行结果:"   o);
        } catch (interruptedexception e) {
  
            e.printstacktrace();
        } catch (executionexception e) {
  
            e.printstacktrace();
        }
        system.out.println("main end");
    }
}
class mycallable implements callable{
  
    @override
    public object call() throws exception {
  //相当于run()方法,不过这个有返回值
        system.out.println("mycallable begin");
        thread.sleep(1000 * 5);
        system.out.println("mycallable end");
        return 1;
    }
}
/**
 * 生产者消费者模式
 */
class thread14{
  
    public static void main(string[] args) {
  
        list
网站地图