首页 > 代码库 > 黑马程序员-学习日记(多线程间的通信)

黑马程序员-学习日记(多线程间的通信)

//将资源封装成对象class Resour{    String name;    String gender;}//将线程执行的任务封装成对象class Input implements Runnable{       private Resour r;    Input(Resour r)    {        this.r = r;    }    public void run()    {        int x =0;        while(true)        {            if(x==0)            {                r.name = "Travis";                r.gender = "male";            }            else            {                r.name = "张妙";                r.gender = "女性";            }            x = (x+1)%2;            }    }}class Output implements Runnable{    private Resour r;    Output(Resour r)    {        this.r = r;    }    public void run()    {        while(true)        {            System.out.println(r.name+" "+r.gender);        }    }}class myLock{    static Object lockA = new Object();    static Object lockB = new Object();} class mlpcDemo {    public static void main(String[] args)     {        Resour r = new Resour();        Input in = new Input(r);        Output out = new Output(r);        Thread th0 = new Thread(in);        Thread th1 = new Thread(out);                th0.start();        th1.start();    }}

于是,我们给赋值的代码块加上同步。这里要注意必须明确哪些代码是要同步的。

//将资源封装成对象class Resour{    String name;    String gender;}//将线程执行的任务封装成对象class Input implements Runnable{    private Resour r;    Object obj = new Object();    Input(Resour r)    {        this.r = r;    }    public void run()    {        int x =0;        synchronized(obj)        {
           while(true) { if(x==0) { r.name = "Travis"; r.gender = "male"; } else { r.name = "张妙"; r.gender = "女性"; } x = (x+1)%2; } } }}class Output implements Runnable{ private Resour r; Output(Resour r) { this.r = r; } public void run() { while(true) { System.out.println(r.name+" "+r.gender); } }}class myLock{ static Object lockA = new Object(); static Object lockB = new Object();} class mlpcDemo { public static void main(String[] args) { Resour r = new Resour(); Input in = new Input(r); Output out = new Output(r); Thread th0 = new Thread(in); Thread th1 = new Thread(out); th0.start(); th1.start(); }}

表面上看,赋值代码块被加上了同步,但运行的结果依然出现了姓名和性别乱搭配的情况。

于是分析原因,定义同步有两个前提,首先Input和Output这两个线程并未使用同一个锁。

其次,仔细观察下列代码:

Thread th0 = new Thread(in);Thread th1 = new Thread(out);
th0.start();
th1.start();

无论Input还是Output都只有一条线程在执行!

 

黑马程序员-学习日记(多线程间的通信)