您的位置:首页 > 职场人生

黑马程序员_day12 多线程(线程间通信,停止线程,守护线程,Join方法,优先级)

2012-08-25 23:53 417 查看
---------------------- android培训、java培训 期待与您交流! ----------------------

一:线程间通信。

1,Input -->资源 -->Output

2,思考1:wait(),notifyAll(),用来操作线程为什么定义在了Object类中?

a,这些方法存在于同步中。

b,使用这些方法时必须要表示所属的同步的锁。

c,锁可以使任意对象,所以任意对象调用的方法一定定义Object类中。

思考2:wait(),sleep()有什么区别?

a,wait():释放资源,释放锁。

b,sleep():释放资源,不释放锁。

二:同步.java。

进程:正在执行的程序。

线程:是进程中用于控制程序执行的控制单元(执行路径,执行情景)

进程中至少有一个线程。

对于JVM,启动时,只好有两个线程:jvm的主线程。jvm的垃圾回收线程。

如何在程序中自定义线程呢?

Java给我们提供了对象线程这类事物的描述。该类是Thread

该类中定义了,

创建线程对象的方法(构造函数).

提供了要被线程执行的代码存储的位置(run())

还定义了开启线程运行的方法(start()).

同时还有一些其他的方法用于操作线程:

static Thread currentThead():

String getName():

static void sleep(time)throws InterruptedException:

要运行的代码都是后期定义的。

所以创建线程的第一种方式是:继承Thread类。原因:要覆盖run方法,定义线程要运行的代码。

步骤:

1,继承Thread类。

2,覆盖run方法。将线程要运行的代码定义其中。

3,创建Thread类的子类对象,其实就是在创建线程,调用start方法。

如果自定义的类中有多线程要运行的代码。但是该类有自己的父类。

那么就不可以在继承Thread。怎么办呢?

Java给我们提供了一个规则。Runnable接口。

如果自定义类不继承Thread,也可以实现Runnable接口。并将多线程要运行的代码存放在Runnable的run方法中。

这样多线程也可以帮助该类运行。

这样的操作有一个好处:避免了单继承的局限性。

创建线程的第二种方式:实现Runnable接口。

步骤:

1,定义了实现Runnable接口。

2,覆盖接口的run方法。将多线程要运行的代码存入其中。

3,创建Thread类的对象(创建线程),并将Runnable接口的子类对象作为参数传递给Thread的构造函数。

为什么要传递?因为线程要运行的代码都在Runnable子类的run方法中存储。所以要将该run方法所属的对象

传递给Thread。让Thread线程去使用该对象调用其run方法。

4,调用Thread对象的start方法。开启线程。

动手写代码。

两种方式的特点:

实现方式,因为避免了单继承的局限性,所以创建线程建议使用第二种方式。

##############################

#第一重点:创建线程的两种方式#

##############################

作为了解:

线程的状态。

1,被创建。

2,运行。

3,冻结。

4,消亡。

其实还有一种特殊的状态:临时状态。

该临时状态的特点:

具备了执行资格,但不具备执行权。

冻结状态的特点:

放弃了执行资格。

多线程具备随机性。因为是由cpu不断的快速切换造成的。

就有可能会产生多线程的安全问题。

问题的产生的原因:

几个关键点:

1,多线程代码中有操作共享数据。

2,多条语句操作该共享数据。

当具备两个关键点时,

有一个线程对多条操作共享数据的代码执行的一部分。还没有执行完,另一个线程开始参与执行。

就会发生数据错误。

解决方法:

当一个线程在执行多条操作共享数据代码时,其他线程即使获取了执行权,也不可以参与操作。

Java就对这种解决方式提供了专业的代码。

同步

同步的原理:就是将部分操作功能数据的代码进行加锁。

示例:火车上的卫生间。

同步的表现形式:

1,同步代码块。

2,同步函数。

两者有什么不同:

同步代码块使用的锁是任意对象。

同步函数使用的锁是this。

注意:对于static的同步函数,使用的锁不是this。是 类名.class 是该类的字节码文件对象。

涉及到了单例设计模式的懒汉式。

同步的好处:解决了线程的安全问题。

弊端:

较为消耗资源。

同步嵌套后,容易死锁。

要记住:同步使用的前提:

1,必须是两个或者两个以上的线程。

2,必须是多个线程使用同一个锁。

这是才可以称为这些线程被同步了。

死锁代码一定会写。但开发时一定注意避免。

##############################

#第二重点:同步的所有特性 #

##############################

/*

class Thread

{

private Runnable target;

Thread()

{

}

Thread(Runnable target)

{

this.target = target;

}

public void run()

{

if(target!=null)

target.run();

}

}

class Test implements Runnable

{

public void run()

{}

}

main()

{

Test q = new Test();

Thread t = new Thread(q);

}

class Demo extends Thread

{

public void run()

{

}

}

class

{

public static void main(String[] args)

{

System.out.println("Hello World!");

}

}

*/

三:解决安全问题,等待唤醒机制,代码优化。

/*

线程间通讯:

其实就是多个线程在操作同一个资源,

但是操作的动作不同。

*/

class Res

{

private String name;

private String sex;

private 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();

}

}

}

class InputOutputDemo2

{

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();

*/

}

}

四:线程间通信-生产消费者。

class ProducerConsumerDemo

{

public static void main(String[] args)

{

Resource r = new Resource();

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();

}

}

/*

对于多个生产者和消费者。

为什么要定义while判断标记。

原因:让被唤醒的线程再一次判断标记。

为什么定义notifyAll,

因为需要唤醒对方线程。

因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。

*/

class Resource

{

private String name;

private int count = 1;

private boolean flag = false;

// t1 t2

public synchronized void set(String name)

{

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()

{

while(!flag)

try{wait();}catch(Exception e){}//t3(放弃资格) t4(放弃资格)

System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);

flag = false;

this.notifyAll();

}

}

class Producer implements Runnable

{

private Resource res;

Producer(Resource res)

{

this.res = res;

}

public void run()

{

while(true)

{

res.set("+商品+");

}

}

}

class Consumer implements Runnable

{

private Resource res;

Consumer(Resource res)

{

this.res = res;

}

public void run()

{

while(true)

{

res.out();

}

}

}

五:多线程(线程间通信-生产者消费者JDK5.0升级版)

import java.util.concurrent.locks.*;

class ProducerConsumerDemo2

{

public static void main(String[] args)

{

Resource r = new Resource();

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();

}

}

/*

JDK1.5 中提供了多线程升级解决方案。

将同步Synchronized替换成现实Lock操作。

将Object中的wait,notify notifyAll,替换了Condition对象。

该对象可以Lock锁 进行获取。

该示例中,实现了本方只唤醒对方操作。

Lock:替代了Synchronized

lock

unlock

newCondition()

Condition:替代了Object wait notify notifyAll

await();

signal();

signalAll();

*/

class Resource

{

private String name;

private int count = 1;

private boolean flag = false;

// t1 t2

private Lock lock = new ReentrantLock();

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();//t1,t2

this.name = name+"--"+count++;

System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);

flag = true;

condition_con.signal();

}

finally

{

lock.unlock();//释放锁的动作一定要执行。

}

}

// t3 t4

public void out()throws InterruptedException

{

lock.lock();

try

{

while(!flag)

condition_con.await();

System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);

flag = false;

condition_pro.signal();

}

finally

{

lock.unlock();

}

}

}

class Producer implements Runnable

{

private Resource res;

Producer(Resource res)

{

this.res = res;

}

public void run()

{

while(true)

{

try

{

res.set("+商品+");

}

catch (InterruptedException e)

{

}

}

}

}

class Consumer implements Runnable

{

private Resource res;

Consumer(Resource res)

{

this.res = res;

}

public void run()

{

while(true)

{

try

{

res.out();

}

catch (InterruptedException e)

{

}

}

}

}

六:停止线程和守护线程。

1,定义循环结束标记。

a,因为线程运行代码一般都是循环,只要控制了循环即可。

2,使用interupt(中断)方法。

b,该方法是结束线程的冻结状态,使线程回到运行状态中来。

注意:stop方法已经过时不再使用。

/*

stop方法已经过时。

如何停止线程?

只有一种,run方法结束。

开启多线程运行,运行代码通常是循环结构。

只要控制住循环,就可以让run方法结束,也就是线程结束。

特殊情况:

当线程处于了冻结状态。

就不会读取到标记。那么线程就不会结束。

当没有指定的方式让冻结的线程恢复到运行状态是,这时需要对冻结进行清除。

强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。

Thread类提供该方法 interrupt();

*/

class StopThread implements Runnable

{

private boolean flag =true;

public 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)

{

//st.changeFlag();

//t1.interrupt();

//t2.interrupt();

break;

}

System.out.println(Thread.currentThread().getName()+"......."+num);

}

System.out.println("over");

}

}

七:多线程-join方法。

1,

/*

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().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(Thread.MAX_PRIORITY);

t2.start();

//t1.join();

for(int x=0; x<80; x++)

{

//System.out.println("main....."+x);

}

System.out.println("over");

}

}

八:多线程-优先级&yield方法。

class MyThread extends Thread{

public void run(){

try {

Thread.currentThread().sleep(3000);

} catch (InterruptedException e) {

}

System.out.println("MyThread running");

}

}

public class ThreadTest{

public static void main(String argv[]) {

MyThread t = new MyThread();

t.run();

t.start();

System.out.println("Thread Test");

}

}

/*

代码分析过程:

MyThread t = new MyThread();

创建了一个线程。

t.run();

调用MyThread对象的run方法。

这是只有一个线程在运行就是主线程。

当主线程执行到了run方法中的sleep(3000);时。

这是主线程处于冻结状态。程序并没有任何执行。

当3秒过后,主线程打印了 MyThread running。 run方法执行结束。

t.start();

开启了t线程。

有两种可能情况。

第一种,主线程在只执行了t.start()后,还具有执行权,继续往下执行,

打印了Thread Test。主线程结束。

t线程获取执行权,调用自己的run方法。然后执行的sleep(3000);冻结3秒。

3秒后,打印MyThread running t线程结束,整个程序结束。

第二种情况:

主线程执行到t.start();开启了t线程,t线程就直接获取到了执行权。

就调用自己的run方法。

指定到sleep(3000).t线程冻结3秒,这是t线程就是释放了执行权。

那么主线程开始执行打印了Thread Test,主线程结束。

等到3秒后,t线程打印MyThread running ,然后t线程结束。

程序结束。

*/

2,

class test_parent

{

int x = 5;

int y = 10;

void set_value(int a, int b)

{

x = a;

y = b;

}

int get_1()

{

return this.x + this.y;

}

int get_2()

{

return x - y;

}

}

class test_4 extends test_parent

{

int y;

test_4(int a)

{

y = a;

}

void set_value(int a, int b)

{

x = a;

y = b;

}

int get_2()

{

return y;

}

}

class Test2

{

public static void main(String[] args)

{

test_4 a1=new test_4(1);

int x = a1.get_1();

System.out.println("x="+x);

}

}

/*

如果用下面几种不同的方法加载类,写出要求的结果:

(3) 用 test_4 a1=new test_4(1) 后;a1.get_1()的内容为_____ 。

(4) 用 test_4 a1=new test_4(-1) ;a1.set _value(5,5) 后;a1.get_2()的内容为

_____。

*/

---------------------- android培训、java培训 期待与您交流! ----------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐