您的位置:首页 > 编程语言 > Java开发

JAVA基础之多线程详解

2014-03-10 18:48 543 查看
JAVA基础之多线程详解

在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这是此方法的局限。

在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比继承Thread类有如下好处:

1、避免点继承的局限,一个类可以继承多个接口。

2、适合于资源的共享

一、通过Thread类来实现多线程
1、定义类继承Thread。
2、复写Thread类中的run方法,目的:将自定义代码存储在run方法。让线程运行。
3、调用线程的start方法,该方法两个作用:启动线程,调用run方法。

<span style="font-size:18px;">public class ThreadDemo {
public static void main(String[] args) {
Test t1 = new Test("one--");
Test t2 = new Test("two++++");
t1.start();	//t1线程
t2.start();	//t2线程
for(int x=0;x<50;x++){	//主线程打印
System.out.println("main--"+x);
}
}
}
class Test extends Thread{ //通过继承Thread来实现多线程!
Test(String name){
super(name);
}
public void run(){
for(int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+"run..."+i);
}
}
}</span>

二、通过Runnable接口来实现多线程
1、定义类实现Runnable接口
2、覆盖Runnable接口中的run方法,将线程要运行的代码存放在该run方法中。
3、通过Thread类建立线程对象。
4、将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数,为什么要将Runnable接口的子类对象传递给Thread的构造函数。因为,自定义的run方法所属的对象是Runnable接口的子类对象。所以要让线程去指定指定对象的run方法,就必须明确该run方法所属对象。
5、调用Thread类的start方法开启线程并调用Runnable接口子类的run方法。

<span style="font-size:18px;">public class ThreadDemo{
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket implements Runnable//实现Runnable接口,或者继承Thread对象
{
private  int tick = 100;
public void run()
{
while(true)
{
if(tick>0)	//如果大于0则显示某个进程卖了哪张票,并自减
{
System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);
}
else	//小于0退出
break;
}
}
}</span>

三、线程安全之同步
Java对于多线程的安全问题提供了专业的解决方式,就是同步代码块。
synchronized(对象)
{
需要被同步的代码
}
对象如同锁。持有锁的线程可以在同步中执行。
没有持有锁的线程即使获取cpu的执行权,也进不去,因为没有获取锁。
同步的前提:
1、必须要有两个或者两个以上的线程。
2、必须是多个线程使用同一个锁。
必须保证同步中只能有一个线程在运行。

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

弊端:多个线程需要判断锁,较为消耗资源。

四、生产者消费者详解(代码都有详细注释)

<span style="font-size:18px;">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();

}
}
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)//同步代码块生产
{
while(flag)//判断标记是否有数据,如果true就等待,false就生产
try{this.wait();}catch(Exception e){}//等待
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;		this.notifyAll();//notify往往唤醒的是线程池中的第一个,使用notify会造成死锁,notifyAll是通知所有
}
public synchronized void out()//同步代码块消费
{
while(!flag)//判断标记是否有数据,如果true就消费,false就等待
try{wait();}catch(Exception e){}//等待
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();
}
}
}</span>

五、新版本生产者及消费者
JDK1.5 中提供了多线程升级解决方案。
将同步Synchronized替换成现实Lock操作。
将Object中的wait,notify notifyAll,替换了Condition对象。
该对象可以Lock锁 进行获取。
该示例中,实现了本方只唤醒对方操作。
Lock:替代了Synchronized(lock 、unlock、newCondition())
Condition:替代了Object wait notify notifyAll (await()、signal()、signalAll())

<span style="font-size:18px;">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();
}
}
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();//创建 一个锁对象
private Condition condition_pro = lock.newCondition();//根据锁创建一个Condition对象
private Condition condition_con = lock.newCondition();
public  void set(String name)throws InterruptedException
{
lock.lock();//上锁
try
{
while(flag)
condition_pro.await();//等待
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;
condition_con.signal();//唤醒消费者
}
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_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)
{
}
}
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息