多个线程抢占一个资源
1.俩人抢5个苹果
- 只能用实现 Runnable接口的方式去实现多线程;用Thread类继承不管用;
- 避免将循环写道同步锁内;否则会造成死锁的情况
苹果类实现多线程实现Runnable()类;同步锁锁的是资源或者控制资源的方法
--------伪代码
public class Apple implements Runnable{
int count 5;
@override
public void run(){
while(count>0){
if(count<=0){
break;
}
synchronized(this){
System.out.println(name+count+"个苹果");
}
count--;
Thread.sleep(5000);
}
}
}
class Test
Apple a=new Apple();
Thread s1=new Thread(a,"小红");
Thread s2=new Thread(a,"小李");//通过Thread a=new Thread() 来新建线程;这是创建了俩线程分别为s1和s2
多个线程完成同个功能,互不干扰
- 迅雷下片的案列
- 继承Thread类或者实现Runnable接口都可以实现这个功能
第一种:
实现Runnable接口
Thunder a=new Thunder();
Thread s1=new Thread(a,“复仇者联盟”);
Thread s2 =new Thread(a,“钢铁侠”);
Thread s3=new Thread(a,“蜘蛛侠”);
Thread s4=new Thread(a,“床下有人”);//通过Thread新建线程来完成多个线程 传递功能参数a;就这样 多个线程完成相同的功能互不干扰
–伪代码
class Thunder implements Runnable{
@override
public run(){
for(int i=1;i<101;i++){
System.out.println(Thread.currentThread().getName()+“下载了”+i+"%");
Thread.sleep(4000);
}
}
}
class Test{
Thunder a=new Thunder();
Thread s1=new Thread(a,“钢铁侠”);
Thread s2=new Thread(a,“美国队长”);
Thread s3=new Thread(a,“超人之钢铁之躯”);
s1.start();
s2.start();
s3.start();
}
第二种:
继承Thread类
资源类直接就有线程的能力
class Thunder extends Thread{
String name;
public Thunder(String name){
this.name=name;
}
@override
public void run(){
for(int i=1;i<101;i++){
System.out.println(name+“下载了”+i+"%");
}
Thread.sleep(4000);
}
}
class Test{
public static void main(String[] args){
Thunder s1=new Thunder();
Thunder s2=new Thunder();
Thunder s3=new Thunder();
s1.start();
s2.start();
s3.start();
}
}
线程之间的通讯
- 面包师和售货员
- 同步锁放在Shop类中;锁就是同步方法;使方法在执行时相互制约 而方法的执行就是对某个资源进行操纵
加锁的过程就是找到多个线程相同的资源或不同的资源;在资源和线程方法的媒介上加锁
老师解释的是要操纵同一个资源 面包 它的有无决定线程的起始
public class Shop{//这个类不是线程,算是资源的存储地
int count;
Random r=new Random();
public synchronized void make(){
if(count==0){
count=r.random(20)+1;
}
this.notify();
this.wait();
public synchronized void sell(){
while(count>0){
int a=r.nextInt(count)+1;
System.out.println(卖出a个);
count-=a;
}
this.notify);
this.wait();
}
}
}
public class Soler implements Runnable{
Shop shop;
public Soler(Shop shop){
this.shop=shop;
}
@override
public void run(){
while(true){
shop.sell();
}
}
}
public class maker implements Runnable{
Shop =shop;
public maker(Shop shop){
this.shop=shop;
}
@overrifr
public void run(){
while(true){
shop.make();
}
}
}
public class Test{
Shop shop =new Shop();
maker s1=new maker(shop);
Soler s2=new Soler(shop);
Thread a1=new Thread(s1);
a1.start();
Thread a2=new Thread(s2);
a2.start();
}