线程实现的主要两种方式
一:继承Thread类
class Ticket extends Thread{ //继承Thread
private static int ticket = 50; //static生命周期较长
@Override
public void run() { //重写run方法
while(ticket>0){
System.out.println(Thread.currentThread().getName()+"售票"+ticket);
ticket--;
}
}
}
二:接Runnable接口
class Sale implements Runnable{
private int pill = 50;
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (this) {
if(pill>0){
System.out.println(Thread.currentThread().getName()+"药丸"+pill--);
}else{
break;
}
}
}
}
}
死锁
public class DeathKey {
private static String co = "kun"; //两把钥匙
private static String cc = "tanaka";
public static void main(String[] args) {
new Thread(){ //匿名局部类线程
public void run(){
while(true){
synchronized(co){
System.out.println(Thread.currentThread().getName()+"这是"+co+"那是"+cc);
synchronized (cc) {
System.out.println(Thread.currentThread().getName()+"这里"+cc);
}
}
}
}
}.start();
new Thread(){
public void run(){
while(true){
synchronized(cc){
System.out.println(Thread.currentThread().getName()+"这是"+cc+"那是"+co);
synchronized (co) {
System.out.println(Thread.currentThread().getName()+"这里"+co);
}
}
}
}
}.start();
}
}
运行结果
如上图所示,后台还在运行但是Thread1才开始走就被锁住
死锁产生的原因:线程一不释放锁,线程二无法继续进行,因争夺有限的资源而陷入死锁
为了避免出现死锁,不要出现同步代码块嵌套