线程,锁,synchornize

 这里不调用run()方法是因为run()方法只是普通方法,不能作为线程,start()才是线程

public class thread01 {
    public static void main(String[] args) throws InterruptedException {
        Cat cat = new Cat();//创建cat对象,当作线程使用
        cat.start();//启动
        //当main线程启动 子线程thread-0,主线程不会阻塞,会继续运行
        //main线程和子线程thread-0交替运行
        System.out.println("主线程"+Thread.currentThread().getName());
        for (int i = 0; i < 10; i++) {
            System.out.println("主线程i="+i);
            Thread.sleep(1000);
        }


    }
}
class Cat extends Thread{
    int time = 0;
    public void run(){
        while (true) {
            //线程每隔一秒输出一次
            System.out.println("喵喵" + (++time) + "线程是" + Thread.currentThread().getName());

            try {
                Thread.sleep(1000);//线程休眠一秒钟
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (time == 80){
                break;
            }
        }
    }
}

为什么要用start()方法而不是run()方法

用run方法此时线程就只有main方法在走,调用完一个方法在调用下一个方法,没有启动线程,这是串行

 而用start方法就会调用jvm里面的start0方法再调用run方法,这时候调用了线程,是并行的

public class thread02 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        //dog不能调用start
        //创建Thread对象,把dog(实现Runnable)放入Thread
        Thread thread = new  Thread(dog);
        thread.start();

        
    }
}
class Dog implements Runnable{//通过实现Runnable接口,开发线程
    int count = 0;

    @Override
    public void run() {
        while (true){
            System.out.println("旺旺" + (++count)+ Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

 

 yield是由cpu来决定执行哪个线程,如果当cpu资源紧缺时候yield就会生效,优先执行指定线程,如果当cpu资源充裕时候yield不生效

join则必定会生效,优先执行指定线程

 

 这时,main退出后,子程序也会退出

线程同步 

 5.非静态方法加锁

synchronized(this)+代码块

 synchronized(object)+代码块

class Sell03 implements Runnable{
    private int ticketNum = 100;
    private boolean loop = true;
    Object object =  new Object();

    public void sell()  {
        synchronized (object) {
            if (ticketNum <= 0) {
                System.out.println("售票结束");
                loop = false;
                return;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票"
                    + "剩余票数=" + (--ticketNum));
        }
    }

6.静态方法加锁

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值