一百零五、实现多线程
(1)、继承Thread类(Thread类也实现的Runnable接口)
public class Thread1 extends Thread {
@Override
public void run() {
while(true) {
//设置线程名称
Thread.currentThread().setName("名字");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}//得到线程名称
System.out.println(Thread.currentThread().getName());
}
}
}
(2)、实现Runnable接口
public class Thread1 implements Runnable{
@Override
public void run() {
while (true) {
//设置线程名称
Thread.currentThread().setName("名字");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}//得到线程名称
System.out.println(Thread.currentThread().getName());
}
}
}
一百零六、线程的抢占式、
设置线程的优先级
t1.setPriority(1);
获取线程的优先级
t1.getPriority();
插队
join();
一百零七、锁(synchronized)
public class PhoneGetTic extends Thread {
private Tickets t;
public PhoneGetTic(Tickets t) {
this.t=t;
}
@Override
public void run() {
while(true) {//不断的拿锁
synchronized(t) {//拿到锁
if(t.getNum()==1) {
System.out.println("票没了。。。。。");
break;
}
t.reduce();
Thread.currentThread().setName("手机");
System.out.println(Thread.currentThread().getName()+"买了一张"+",当前还剩"+t.getNum());
}//拿到锁
}
}
}
一百零八、死锁
死锁的概念:死锁的形式为两个(多个)线程相互等待来自对方的锁;
解决死锁:调整锁的顺序:调用的顺序保持一致。
代码实现
(1)、线程一
synchronized(o1) {//拿到o1锁
System.out.println(this.getName()+"拿到了o1锁");
synchronized(o2) {//拿到o2锁
System.out.println(this.getName()+"拿到了o2的锁");
}//释放锁
}//释放锁
(2)、线程二
synchronized(o2) {//拿到o2锁
System.out.println(this.getName()+"拿到了o2锁");
synchronized(o1) {//拿到o1锁
System.out.println(this.getName()+"拿到了o1的锁");
}//释放锁
}//释放锁
一百零九、线程之间的通信
private Product p;
(1)、唤醒在当前资源上等待的所有线程(等待之前,唤醒所有线程): p.notifyAll();
(2)、当前线程在当前资源上等待,并释放锁:
p.wait();