Java多线程实战

    实习的时候发现多线程方面知识比较薄弱,这段时间在学习汪文君老师的《Java高并发编程实战》,并做一些学习笔记,供以后复习。

    我们在单线程情况下执行两个方法,默认是按照顺序执行的,如下面的读写数据库操作:

public class TryConcurrency1 {

    public static void main(String[] args) {
        readFromDataBase();
        writeDataToFile();
    }

    private static void readFromDataBase() {
        //read data from database and handle it.
        try {
            println("Test1:"+"Begin read data from db.");
            Thread.sleep(1000 * 3L);
            println("Test1:"+"Read data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        println("Test1:"+"The data handle finish and successfully.");
    }

    private static void writeDataToFile() {
        try {
            println("Test2:"+"Begin write data to file.");
            Thread.sleep(1000 * 10L);
            println("Test2:"+"Write data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        println("Test2:"+"The data handle finish and successfully.");
    }

    private static void println(String message) {
        System.out.println(message);
    }
}

输出结果为:


如果我们要并行的读写数据库,那么我们就要用到多线程操作,如:

public class TryConcurrency1 {

    public static void main(String[] args) {
       Thread t=new Thread("read-Thread"){
           @Override
           public void run() {
               println(Thread.currentThread().getName());//main
               readFromDataBase();
           }
       };
       t.start();
       //通过匿名内部类的方式
        new Thread("write-Thread"){
            @Override
            public void run() {
                writeDataToFile();
            }
        }.start();
    }

    private static void readFromDataBase() {
        //read data from database and handle it.
        try {
            println("Test1:"+"Begin read data from db.");
            Thread.sleep(1000 * 3L);
            println("Test1:"+"Read data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        println("Test1:"+"The data handle finish and successfully.");
    }

    private static void writeDataToFile() {
        try {
            println("Test2:"+"Begin write data to file.");
            Thread.sleep(1000 * 10L);
            println("Test2:"+"Write data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        println("Test2:"+"The data handle finish and successfully.");
    }

    private static void println(String message) {
        System.out.println(message);
    }
}

值得注意的是: 创建Thread并非一个线程,只有当启动之后才会成为一个线程。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值