Day12 多线程
——线程间通信、停止线程、守护线程、join方法、优先级和yield方法
线程间通信
其实就是多个线程在操作同一个资源,但是操作的动作不同。
class Res
{
String name;
String sex;
}
class Input implements Runnable
{
//Res r = new Res();
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
//r.name;
//r.sex;
int x = 0;
//boolean b = true;
while(true)
{
if(x == 0)
//if(b)
{
r.name = "mike";
r.sex = "man";
//b = false;
}
else
{
r.name = "莉莉";
r.sex = "女女女女女";
//b = b - true;
}
x = (x + 1)%2;
}
}
}
class Output implements Runnable
{
//Res r = new Res();
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
//r.name;
//r.sex;
while(true)
{
System.out.println(r.name+"..."+r.sex);
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
//一堆煤放在两个大卡车上,一个进的一个出的
//放在两条公路上,公路开启
Res r = new Res();
Input in =new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
产生错误原因:
Input在往里面寸mike和man,当往里存莉莉的时候,刚存完莉莉就被输出线程获取到了执行权,就把莉莉和man打印出去。赋值这两个动作是共享数据,被多条语句所操作,结果 输入了名的但是没输出性别的就被输出了。
解决安全问题:
class Res
{
String name;
String sex;
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(x == 0)
{
r.name = "mike";
r.sex = "man";
}
else
{
r.name = "莉莉";
r.sex = "女女女女女";
}
x = (x + 1)%2;
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
System.out.println(r.name+"..."+r.sex);
}
}
}
}
//内存中一共四个类:Input、Output、Res、InputOutputDemo .class
//写上面4个.class或不写,内存中对象r唯一
class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
Input in =new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
等待唤醒机制
输入的线程如果获取了cpu的执行权,输入存储了一个mike man,出了同步之后Input和Output都会再次抢到cpu执行权,输入还会再次抢到执行权,莉莉女输入进去会覆盖前面内容,Input持有执行权后会一直不断录入把前面内容覆盖掉,当某一时刻它的执行权被抢走了Output在cpu会执行多次,把一个值会打印多次,所以造成一大片一大片。原因:cpu切换
需求:往里扔一个值取一个。
class Res
{
String name;
String sex;
boolean falg = false;
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(Exception e){}
//r线程的锁
if(x == 0)
{
r.name = "mike";
r.sex = "man";
}
else
{
r.name = "莉莉";
r.sex = "女女女女女";
}
x = (x + 1)%2;
r.falg = true;
r.notify();//唤醒沉睡的线程
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"..."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
//内存中一共四个类:Input、Output、Res、InputOutputDemo .class
//写上面4个.class或不写,内存中对象r唯一
class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
Input in =new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
wait();
notify();
notifyAll();
都使用在同步中,因为要对持有监视器(锁)的线程操作,所以要在使用在同步中,因为只有同步才具有锁。
为什么这些操作线程的方法要定义在Object类中呢?因为这些方法在操作同步中线程时,都必须要标识他们所操作线程中有的锁。只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒,不可以对不同锁中的线程进行唤醒。
也就是说,等待和唤醒必须是同一把锁。
而锁可以使任意对象,所以可以被任意对象调用的方法定义在Object类中。
class Res
{
String name;
String sex;
boolean falg = false;
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(Exception e){}
//r线程的锁
if(x == 0)
{
r.name = "mike";
r.sex = "man";
}
else
{
r.name = "莉莉";
r.sex = "女女女女女";
}
x = (x + 1)%2;
r.falg = true;
r.notify();//唤醒沉睡的线程
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"..."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
//内存中一共四个类:Input、Output、Res、InputOutputDemo .class
//写上面4个.class或不写,内存中对象r唯一
class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
Input in =new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
代码优化
class Res
{
String name;
String sex;
boolean flag = false;
public synchronized void set(String name,String sex)
{
if(flag)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name + "......" + sex);
flag = false;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
if(x == 0)
r.set("mike","man");
else
r.set("莉莉","女女女女女");
x = (x + 1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
//内存中一共四个类:Input、Output、Res、InputOutputDemo .class
//写上面4个.class或不写,内存中对象r唯一
class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
/*
Input in =new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
*/
}
}
例:生产者消费者
问题:生产两次消费一次
解释:假设生产者获取到了cpu的执行权,生产者有两个t1、t2,消费者有两个t3、t4,假设t1获取到执行权,t1判断为假,不需要等待直接赋值,count++,打印…生产者…生产一次,置为真,notify();notify之后还优可能持有资源,还拥有执行权,又跑到if(flag)为真,wait()等待,t1等待(放弃资格)。此时,t2t3t4都有可能抢到执行权,假设t2抢到执行权,判断if(flag)为真,也wait,t2等待(放弃资格)。剩下t3t4,判断if(!flag)非真为假,不需要等待,打印…消费者…消费一次,flag = false,notify()–>唤醒t1,t1(获取资格)(但没有执行权,此时的执行权在t3手里)。判断if(!flag)非假为真,t3 wait() t3(放弃资格), t4(放弃资格)。t1拥有执行权,count++,打印…生产者…生产一次,t1生产完一个商品以后置为真,notify,唤醒t2(在线程中等待时t2先进去),t1唤醒本方t2,t2(获取资格),现在只有t1具有执行权,如果if(flag)为真 wait,t1(放弃资格)。此时只有t2具有执行权,醒之后直接不判断往下执行,t3t4放弃资格,生产完1个之后没有被消费,又打印…生产者…生产一次,前一个被覆盖了。t3消费一次。
原因:在执行前在上面wait,醒了之后没有再判断flag标记。判断多次,用while。
改成while之后每次都判断,会出现 全部等待,4个全等待。
死锁:我的跟你要,你的跟我要,互相不放
全部等待:大家谁都动不了
t1把自己方唤醒,notify唤醒的是线程之中的第一个,有可能唤醒本方导致数据错乱,加了while之后导致全部等待–>notifyAll,全部唤醒循环判断标记。
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Rescource r = new Rescource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Rescource
{
private String name;
private int count = 1;
private boolean flag = false;
//t1 t2
public synchronized void set(String name)
{
//if(flag)
while(flag)
try{this.wait();}catch(Exception e){}//t1(获取资格),t2等待(获取资格)
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
flag = true;
this.notifyAll();
}
//t3 t4
public synchronized void out()
{
//if(!flag)
while(!flag)
try{this.wait();}catch(Exception e){}//t3(放弃资格),t4(放弃资格)
System.out.println(Thread.currentThread().getName() + "......消费者......" + this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Rescource res;
Producer(Rescource res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.set("+ 商品 +");
}
}
}
class Consumer implements Runnable
{
private Rescource res;
Consumer(Rescource res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
对于多个生产者和消费者。为什么要定义while判断标记。原因:让被唤醒的线程再一次判断标记。
为什么定义notifyAll。因为需要唤醒对方线程。因为只用notify,容易出现只唤醒本方线程的情况,导致程序中的所有线程都等待。
例:生产者消费者——JDK5.0升级版
JDK1.5中提供了多线程升级解决方案。
将同步Synchronized替换成现实Lock操作。将Object中的wait,notify notifyAll,替换了Condition对象。该对象可以Lock锁进行获取。一个锁中可以绑定好几个Condition对象。
给实例中,实现了本方只唤醒对方操作。
JDK1.5之后 提供了显示的锁机制和显示的锁对象上的等待唤醒操作机制,同时把等待唤醒进行封装,封装完一个锁可以对应多个Conditon。把wait notify封装成Condition对象。
没有之前一个锁只能对应一个wait notify。如果想再由一组wait notify,需再建锁需要再建同步,两个锁同步互相嵌套容易形成死锁。
释放锁的动作一定要执行。–>finally{lock.unlock)();}
import java.util.concurrent.locks.*;
class ProducerConsumerDemo2
{
public static void main(String[] args)
{
Rescource r = new Rescource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Rescource
{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();//-->锁
//wait notify应该定义在同步语句中,每一个wait notify都要标识自己所属的锁
//现在同步变成了lock,wait notify变成了condition,condition通过锁获取
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name) throws InterruptedException
{
lock.lock();//获取锁
try
{
while(flag)
condition_pro.await();//等待,没有写catch,要写抛出异常
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
flag = true;
condition.signalAll();//唤醒一个等待线程,唤醒全部
condition_con.signal();//只唤醒另一方
}
finally//finally中存放的一般是释放资源的动作
{
lock.unlock();//释放锁,此句话一定要执行
}
}
public void out() throws InterruptedException
{
lock.lock();
try
{
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName() + "......消费者......" + this.name);
flag = false;
//condition.signalAll();
condition_pro.singal();//只唤醒另一方
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Rescource res;
Producer(Rescource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.set("+ 商品 +");
}
catch (InterruptedException e)
{
}
}
}
}
class Consumer implements Runnable
{
private Rescource res;
Consumer(Rescource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.out();
}
catch (InterruptedException e)
{
}
}
}
}
停止线程
1.定义循环结束标记
因为线程运行代码一般都是循环,只要控制了循环即可。
2.使用interrupt(中断)
该方法是结束线程的冻结状态,使线程回到巡行状态中来。
注:stop方法已经过时不再使用。
如何停止线程?
只有一种,run方法结束。开启多线程运行,运行代码通常是循环的。只要控制住循环,就可以让run方法结束,也就是线程结束。
特殊情况:当线程处于了冻结状态,就不会读取到标记,那么线程就不会结束。
中断状态:冻结状态,不是停止线程(stop方法,线程正在运行,采用方法后就断了停止了),当进入到冻结状态后,相当于被挂起来动不了了,强制清除冻结状态恢复运行状态。
Interrupt方法将处于冻结状态的线程强制恢复到运行状态中来,只有运行才能读标记。
当没有指定的方式让冻结的线程恢复到运行状态时,这是需要对冻结进行清除。强制让线程恢复到运行状态中来(获取运行资格)。这样就可以操作标记让线程结束。
Thread类中提供该方法 interrupt();
class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while (flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + "...Exception");
flag = false;
}
System.out.println(Thread.currentThread().getName() + "...run");
}
}
public void changeFlag()
{
flag = false;
}
}
class StopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 0;
while(true)
{
if(num ++ == 60)
{
//st.changeFlag();
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+ "......" + num);
}
System.out.println("over");
}
}
守护线程(后台线程)
getDaemon():将该线程标记为守护线程或用户线程或后台线程。当正在运行的线程都是守护线程时,Java虚拟机退出。该方法必须在启动线程前调用。
主线程是前台线程,所看到的线程都是前台线程,当把某些线程标记成后台线程后,后台线程特点:开启后和后台线程共同抢夺cpu的执行权运行,开启和运行与前台线程没有区别,就结束时有区别,当所有的前台线程都结束后,后台线程会自动结束。后台依赖于前台。
主线程是前台线程,当主线程结束后,开启的两个线程(守护线程)自动结束。
class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while (flag)
{
System.out.println(Thread.currentThread().getName() + "...run");
}
}
public void changeFlag()
{
flag = false;
}
}
class StopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
int num = 0;
while(true)
{
if(num ++ == 60)
{
break;
}
System.out.println(Thread.currentThread().getName()+ "......" + num);
}
System.out.println("over");
}
}
join方法
join():等待该线程终止。
在进行多线程运算时,(如果满足条件)可以临时加入一个线程,让这个线程运算完,另外一个线程再继续运行。主线程碰着谁的join就等谁,等谁让主线程把执行权放下执行完。
当A线程执行到了B线程的.join()方法时,A就会等待。等B线程都执行完,A才会执行。join可以用来临时加入线程执行。
class Demo implements Runnable
{
public void run()
{
for (int x = 0; x < 70 ; x++ )
{
System.out.println(Thread.currentThread().getName() + "......" + x);
}
}
}
class JoinDemo
{
public static void main(String[] args) throws Exception
{
Demo d = new Demo();
Thread t1 = new Thread(d);
Thread t2 = new Thread(d);
t1.start();
t1.join();//t1抢夺cpu执行权,此时主线程处于冻结状态
//主线程等到t1挂了才能继续执行
t2.start();
for (int x = 0; x<80; x++)
{
System.out.println("main......" + x);
}
System.out.println("over");
}
}
优先级和yield方法
线程组:谁开启就属于那个线程组
优先级:抢资源的频率,所有线程包括主线程默认的优先级都是5,setPriority 设置优先级。
MAX_PRIORITY:线程具有最高优先级 10。
MIN_PRIORITY:线程具有最低优先级 1。
NORM_PRIORITY:线程具有默认优先级 5。
class Demo implements Runnable
{
public void run()
{
for (int x = 0; x<70 ; x++ )
{
System.out.println(Thread.currentThread().toString() + "......" + x);
Thread.yield();//暂停当前正在执行的线程对象,并执行其他线程。
}
}
}
class JoinDemo
{
public static void main(String[] args) throws Exception
{
Demo d = new Demo();
Thread t1 = new Thread(d);
Thread t2 = new Thread(d);
t1.start();
//t1.setPriority(10);
t1.setPriority(Thread.MAX_PRIORITY);
t2.start();
for (int x = 0; x<80; x++)
{
System.out.println("main......" + x);
}
System.out.println("over");
}
}
class ThreadTest
{
public static void main(String[] args)
{
//三个循环,执行完第一个才执行后面连个,如果第一个循环运行很多次后面连个执行不到
//当某些代码需要同时被执行时就用单独的线程进行封装
new Thread()//建立Thread类的子类对象
{
public void run()
{
for (int x = 0; x<100 ; x++)
{
System.out.println(Thread.currentThread().getName() + "......" + x);
}
}
}.start();
for (int x = 0; x<100 ; x++)
{
System.out.println(Thread.currentThread().getName() + "......" + x);
}
Runnable r = new Runnable()//用匿名类
{
public void run()
{
for (int x = 0; x<100 ; x++)
{
System.out.println(Thread.currentThread().getName() + "......" + x);
}
}
};
new Threrad(r).start();
//new Test1().start();
//同单独搞个类,麻烦,直接用匿名内部类
}
}
/*
class Test1 extends Thread
{
public void run()
{
for (int x = 0; x<100 ; x++)
{
System.out.println(Thread.currentThread().getName() + "......" + x);
}
}
}
*/