前言
本次学习主要有线程的优先级和线程同步。
一、线程的优先级
Java提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程。线程调度器按照线程的优先级决定调度哪个线程来执行。
线程优先级用数字表示,范围从1到10,一个线程的缺省优先级是5
Thread.MIN_PRIORITY
=1
Thread.MAX_PRIORITY
=1
Thread.NORM_PRIORITY
=1
获得线程对象的优先级
int getPriority();
设置线程的优先级
void setPriority(int newPriority);
例子
class MyThread1 implements Runnable {
public void run(){
for (int i=0;i<=10;i++){
System.out.println("------------线程5第"+i+"次");
}
}
}
===============================================================================================
public class MyThread2 implements Runnable{
public void run(){
for (int i=0;i<=10;i++){
System.out.println("------------线程6第"+i+"次");
}
}
}
=============================================================================================
public class Thread1 {
public static void main(String[] args) {
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
Thread t5=new Thread(t1);
Thread t6=new Thread(t2);
//设置t5的优先级,在正常的优先级的基础上再提升3个等级
//默认情况下,Thread.NORM_PRIORITY的优先级为5
t5.setPriority(Thread.NORM_PRIORITY+3);
//启动线程
t5.start();
t6.start();
//获取t5的优先级
System.out.println("t5的优先级是"+t5.getPriority());
}
}
结果:
如结果所示,因为线程5的优先级比线程6大,所以线程5抢占资源的能力比线程6大,先执行的概率也会比线程6的大。
二、线程同步
Java中,引入了对象互斥锁的概念,保证共享数据操作的完整性,每个对象都对应于一个可称为“互斥锁”的标记,这个标记保证在任一时刻,只能有一个线程访问该对象
。我们使用synchronized关键字来实现与对象的互斥锁联系,当某个对象被synchronized修饰时,表明该对象在任一时刻只能由一个线程访问。
synchronized
关键字的使用
synchronized(this){
num++;
try{
Thread.sleep(1);
}catch(InterrupteException e){}
System.out.println(name+"你是第"+num+"个使用timer的线程")
//synchronized 还可以放在方法声明中,表示整个方法为同步方法
synchronized public void add(String name){...}
例子:
public class Title {
private static int num=0;
public void add(String name){
synchronized (this){
/*
* 使用synchronized(this)来锁定当前对象,这样就不会再出现两个不同的线程同时访问同一个对象资源的问题了
* 只有当一个线程访问结束后才会轮到下一个线程来访问
28 */
num++;
try {
Thread.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(name+"你是第"+num+"个使用title的线程");
}
}
}
===============================================================================================
public class TestSynch implements Runnable {
Title title=new Title();
@Override
public void run() {
title.add(Thread.currentThread().getName());
}
}
===============================================================================================
public class Thread1 {
public static void main(String[] args) {
TestSynch testSynch=new TestSynch();
Thread t1=new Thread(testSynch);
Thread t2=new Thread(testSynch);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
结果: