《Java开发实战经典》第九章 多线程

1.Java中线程的实现

1)继承Thread类

多线程要执行的功能必须在Run()方法中进行定义

为什么启动线程不能直接使用Run()方法?

线程的运行需要本地操作系统的支持。

如果一个类通过继承Thread类来实现,那么只能调用一次start()方法,如果调用多次,则抛出“IlleagalThreadStateException”异常

class MyThread extends Thread{
    private String name;
    public MyThread(String name){
        this.name=name;
    }
    public void run(){
        for (int i=0;i<5;i++){
            System.out.println(name+":"+i);
        }
    }
}

public class Test {
    public static void main(String args[]) {
        MyThread tha=new MyThread("A");
        MyThread thb=new MyThread("B");
        tha.start();
        thb.start();
    }
}
---------------------------------
A:0
B:0
A:1
A:2
A:3
B:1
B:2
A:4
B:3
B:4

2)实现Runnable接口

class MyThread implements Runnable{
    private String name;
    public MyThread(String name){
        this.name=name;
    }
    public void run(){
        for(int i=0;i<3;i++){
            System.out.println(name+":"+i);
        }
    }
}

public class Test {
    public static void main(String args[]) {
        MyThread tha=new MyThread("A");
        MyThread thb=new MyThread("B");
        Thread t1=new Thread(tha);
        Thread t2=new Thread(thb);
        t1.start();
        t2.start();
    }
}
---------------------------------
B:0
A:0
B:1
A:1
B:2
A:2

在Thread类中提供了public Thread(Runnable target)和public Thread(Runnable target,String name)两个构造方法。这两个构造方法都可以接收Runnable的子类实例对象,所以可以依靠此点启动多线程。

【区别】继承Thread类不适合多个线程共享资源;实现Runnable接口可以方便实现资源共享。

Thread类是Runnable接口的子类,而且使用Runnable接口可以避免单继承局限,以及更加方便的实现数据共享。

但是线程执行完毕之后无法获得一个返回值。

3)实现Callable接口


import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class Mythread implements Callable<String>{
    private int ticket=3;
    public String call() throws Exception{
        for(int x=0;x<100;x++){
            if(this.ticket>0){
                System.out.println("sale ,ticket="+this.ticket--);
            }
        }
        return "ticket is null";
    }
}
public class Test {
    public static void main(String args[]) throws Exception {
        Mythread tha=new Mythread();
        Mythread thb=new Mythread();
        FutureTask<String> task1=new FutureTask<String>(tha);
        FutureTask<String> task2=new FutureTask<String>(thb);
        new Thread(task1).start();
        new Thread(task2).start();
        System.out.println("A returned result is:"+task1.get());
        System.out.println("B returned result is:"+task2.get());
    }
}
---------------------------------
sale ,ticket=3
sale ,ticket=2
sale ,ticket=1
sale ,ticket=3
sale ,ticket=2
sale ,ticket=1
A returned result is:ticket is null
B returned result is:ticket is null

Callable接口只是胜在有返回值上,但Runnable接口是Java最早提供的,也是使用最广泛的接口,所以在实现多线程的时候还是优先考虑使用Runnable接口。

2.线程的状态

创建、就绪、运行、阻塞、终止

3.线程操作的相关方法

取得和设置线程名称

在线程操作时,如果没有为一个线程指定名称,则系统在使用时会为线程分配一个名称,名称格式为Thread-XX。

class Mythread implements Runnable{
    public void run(){
        for(int i=0;i<3;i++) {
            System.out.println(Thread.currentThread().getName() + " :i=" + i);
        }
    }
}
public class Test {
    public static void main(String args[]) throws Exception {
        Mythread mt=new Mythread();
        new Thread(mt).start();
        new Thread(mt,"A").start();
        new Thread(mt).start();
    }
}
---------------------------------
Thread-1 :i=0
A :i=0
Thread-0 :i=0
A :i=1
Thread-1 :i=1
A :i=2
Thread-0 :i=1
Thread-0 :i=2
Thread-1 :i=2

【Java程序运行至少启动几个线程?】

至少启动两个线程。一个是main线程;一个是垃圾收集线程。

判断线程是否启动

isAlive()来测试线程是否已经启动而且仍然在运行。

线程的强制运行

join()让一个线程强制运行。在线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行。

线程的休眠

Thread.sleep();

中断线程

interrupt()

后台线程

setDaemon()

线程的优先级

setPriority()

线程将根据设置其优先级的大小来决定哪个线程会先运行,但是并不一定线程的优先级高就一定会先执行,哪个线程先执行将由CPU的调度决定。

线程的礼让

yield()

将一个线程的操作暂时让给其他线程执行。

4.同步

同步:多个操作在同一个时间段内只能有一个线程进行,其他线程要等待此线程完成之后才可以继续执行。

解决资源的同步操作,可以使用同步代码块和同步方法两种方式完成。

同步代码块

如果在代码块上加上synchronized关键字,则此代码块称为同步代码块。

class Mythread implements Runnable{
    private int ticket=5;
    public void run(){
        for(int i=0;i<100;i++){
            //在使用同步代码块时必须指定一个需要同步的对象,一般都将当前对象this设置为同步对象
            synchronized (this){
                if(ticket>0){
                    try{
                        Thread.sleep(300);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println("sale ticket,ticket="+ticket--);
                }
            }
        }
    }
}


public class Test {
    public static void main(String args[]) throws Exception {
        Mythread mt=new Mythread();
        Thread t1=new Thread(mt);
        Thread t2=new Thread(mt);
        Thread t3=new Thread(mt);
        t1.start();
        t2.start();
        t3.start();
    }
}
---------------------------------
sale ticket,ticket=5
sale ticket,ticket=4
sale ticket,ticket=3
sale ticket,ticket=2
sale ticket,ticket=1

同步方法

class Mythread implements Runnable{
    private int ticket=5;
    public synchronized void sale(){
        if(ticket>0){
            try{
                Thread.sleep(300);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("sale ticket,ticket="+ticket--);
        }
    }
    public void run(){
        for(int i=0;i<100;i++){
            this.sale();
        }
    }
}
public class Test {
    public static void main(String args[]) throws Exception {
        Mythread mt=new Mythread();
        Thread t1=new Thread(mt);
        Thread t2=new Thread(mt);
        Thread t3=new Thread(mt);
        t1.start();
        t2.start();
        t3.start();
    }
}
---------------------------------
sale ticket,ticket=5
sale ticket,ticket=4
sale ticket,ticket=3
sale ticket,ticket=2
sale ticket,ticket=1

同步实际上会造成性能的降低。

5.死锁

死锁:两个进程都在等待彼此先完成,造成了程序的停滞状态,一般程序的死锁是在程序运行时出现。

死锁是一种需要回避的代码,并且在多线程的开发中,死锁都是需要通过大量测试才可以被检测出来的一种程序非法状态。

同步与死锁的应用

多个线程共享同一资源时需要进行同步,以保证资源操作的完整性,但是过多的同步就有可能产生死锁,导致程序进入停滞状态。

6.实例——生产者消费者问题

class Info{
    private String name="lwh";
    private String content="申城最明亮的少女";
    private boolean flag=false;

    public synchronized void set(String name,String content){
        if(!flag){
            try{
                super.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.setName(name);
        try {
            Thread.sleep(300);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        this.setContent(content);
        flag=false;
        super.notify();
    }

    public synchronized void get(){
        if(flag){
            try{
                super.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        try{
            Thread.sleep(100);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(this.getName()+"-->"+this.getContent());
        flag=true;
        super.notify();
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Producer implements Runnable{
    private Info info=null;
    public Producer(Info info){
        this.info=info;
    }
    public void run(){
        boolean flag=false;
        for(int i=0;i<50;i++){
            if(flag){
                this.info.set("lwh","申城最明亮的少女");
                flag=false;
            }else{
                this.info.set("wwj","京城最明亮的少年");
                flag=true;
            }
        }
    }
}
class Consumer implements Runnable{
    private Info info=null;
    public Consumer(Info info){
        this.info=info;
    }
    public void run(){
        for(int i=0;i<50;i++){
            try{
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            this.info.get();
        }
    }
}

public class Test {
    public static void main(String args[]) {
        Info i=new Info();
        Producer pro=new Producer(i);
        Consumer con=new Consumer(i);
        new Thread(pro).start();
        new Thread(con).start();
    }
}
---------------------------------
【问题一】生产者添加了信息的名称,还没来得及添加内容,消费者把这个消息的名称和上个消息的内容组合在了一起。
lwh-->京城最明亮的少年
wwj-->申城最明亮的少女
【问题二】重复取出和重复生产问题
lwh-->申城最明亮的少女
lwh-->申城最明亮的少女
lwh-->申城最明亮的少女
【正常情况】
lwh-->申城最明亮的少女
wwj-->京城最明亮的少年
lwh-->申城最明亮的少女
wwj-->京城最明亮的少年

【面试题】解释sleep()和wait()的区别?

sleep():Thread类定义的static方法,表示线程休眠,将执行机会给其他线程,但是监控状态依然保持,休眠时间到即会自动恢复。

wait():Object类定义的方法,表示线程等待,一直到执行了notify()或notifyall()才结束等待。

7.线程的生命周期

在多线程的开发中,可以通过设置标识位的方法停止一个线程的运行。

class MyThread implements Runnable{
    private boolean flag=true;//定义标识位属性
    public void run(){
        int i=0;
        while(this.flag){
            while(true){
                System.out.println(Thread.currentThread().getName()+"running,i="+(i++));
            }
        }
    }
    public void stop(){
        this.flag=false;
    }
}

public class Test {
    public static void main(String args[]) {
        MyThread mt=new MyThread();
        Thread t=new Thread(mt,"线程");
        t.start();
        mt.stop();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
信息数据从传统到当代,是一直在变革当中,突如其来的互联网让传统的信息管理看到了革命性的曙光,因为传统信息管理从时效性,还是安全性,还是可操作性等各个方面来讲,遇到了互联网时代才发现能补上自古以来的短板,有效的提升管理的效率和业务水平。传统的管理模式,时间越久管理的内容越多,也需要更多的人来对数据进行整理,并且数据的汇总查询方面效率也是极其的低下,并且数据安全方面永远不会保证安全性能。结合数据内容管理的种种缺点,在互联网时代都可以得到有效的补充。结合先进的互联网技术,开发符合需求的软件,让数据内容管理不管是从录入的及时性,查看的及时性还是汇总分析的及时性,都能让正确率达到最高,管理更加的科学和便捷。本次开发的医院后台管理系统实现了病房管理、病例管理、处方管理、字典管理、公告信息管理、患者管理、药品管理、医生管理、预约医生管理、住院管理、管理员管理等功能。系统用到了关系型数据库中王者MySql作为系统的数据库,有效的对数据进行安全的存储,有效的备份,对数据可靠性方面得到了保证。并且程序也具备程序需求的所有功能,使得操作性还是安全性都大大提高,让医院后台管理系统更能从理念走到现实,确确实实的让人们提升信息处理效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值