JAVA 多线程,多线程

package com.example.web1_2.thrades;

//创建线程
//1、 继承Thread类,重写run()方法
// MyTrade myTrade=new MyTrade(); myTrade.start();
public class MyThrade extends Thread {

    @Override
    public void run(){
        Thread t1 = new Thread(() -> {
            for(int i = 1; i < 6; i++){
                System.out.println("MyTrade run t1 " + i);
                try {
                    //线程的睡眠(sleep)及中断(interrupt)
                    //当线程实例调用interrupt方法时,睡眠就被了。然后执行catch中的方法。
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    System.out.println("线程睡眠被中断");
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t2 7s end");
            //中断t1线程
            t1.interrupt();
        });

        t1.start();
        t2.start();

        System.out.println("MyThrade end");
    };

    //方法加锁 synchronized 关键字(对象或者类)
    //public synchronized int  getBeans(){...}
    //public int getBean(){synchronized (this){...}}
    // 静态方法,默认使用的是类的class当锁(Table.class)
    //public static synchronized void getBeans(){synchronized (类名.class){...}}
    public synchronized int getInt1(){
        return 0;
    }

    //影响调用 getInt1, 同一时间,只能调用一个。
    public synchronized int getInt2(){
        return 0;
    }

    // 不影响调用getInt1, getInt2
    // 当synchronized作用于静态方法时,其锁就是当前类的class对象锁。
    // 由于静态成员不专属与任何一个实例对象,是类成员,因此通过class对象锁可以控制静态成员的并发操作。
    // 访问静态方法占用的锁是属于当前类对象,而访问非静态synchronized方法占用的锁是属于当前实例对象
    public static synchronized int getInt3(){
        return 0;
    }
}

/*
 2、 实现 Runnable 接口, class Thread implements Runnable

public class Demo {
    public static void main(String[] args) {

        // 任务和线程分离
        Aoo aoo = new Aoo(); // 构建了任务
        Thread t2 = new Thread(aoo); // 把这个任务交给线程去处理
        t2.start();

    }
}

// 创建任务
class Aoo implements Runnable{

    @Override
    public void run() {
        System.out.println("Aoo.run");

    }
}
*/

Java并发之synchronized深入理解

java多线程&线程与进程区别

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值