线程的优先级及线程的同步问题

一.可以使用setPriority方法来设置

线程测优先级 (有可能影响线程的执行顺序)
1- MIN_PRIORITY
10- MAX_PRIORITY
5- MAX_PRIORITY 默认
优先级高的可能先被使用

如结果所示,每次C都会先执行,但只是有可能影响


public class ThreadDemo04 {
    public static void main(String[] args) {
        MyThread1 d1 = new MyThread1();
        MyThread1 d2 = new MyThread1();
        MyThread1 d3 = new MyThread1();
        Thread r1 = new Thread(d1,"A");
        Thread r2 = new Thread(d2,"B");
        Thread r3 = new Thread(d3,"C");
        r1.setPriority(Thread.MIN_PRIORITY);
        r2.setPriority(Thread.NORM_PRIORITY);
        r3.setPriority(Thread.MAX_PRIORITY);
        r1.start();
        r2.start();
        r3.start();
    }
}

class MyThread1 implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<5;i++){
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName()+" "+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


C 0
A 0
B 0
C 1
B 1
A 1
C 2
B 2
A 2
C 3
B 3
A 3
C 4
B 4
A 4

二.线程的同步问题
解决资源共享的问题


public class ThreadDemo05 {
    public static void main(String[] args) {
        MyThreadDemo d1 = new MyThreadDemo();
        Thread t1 = new Thread(d1); 
        Thread t2 = new Thread(d1); 
        Thread t3 = new Thread(d1); 
        t1.start();
        t2.start();
        t3.start();
    }
}

class MyThreadDemo implements Runnable{
    private int ticket = 5;
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
//          synchronized (this) {
//              if(ticket>0){
//                  try {
//                      Thread.sleep(500);
//                  } catch (InterruptedException e) {
//                      // TODO Auto-generated catch block
//                      e.printStackTrace();
//                  }
//                  System.out.println("车票"+ticket--);
//              }
//          }
            tell();

        }
    }

    public synchronized void tell() {
        if(ticket>0){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("车票"+ticket--);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值