Java多线程

2016-10-23  本文已影响0人  A_Coder

线程是指程序在执行过程中,能过执行程序代码的一个执行单元。在Java中,线程有4种状态:运行、就绪、挂起和结束。
进程是指一段正在执行的程序。而线程有时被称为轻量级进程,它是程序执行的最小单元,一个进程可以拥有多个线程,各个线程之间共享程序的内存空间(代码段、数据段和堆空间)及一些进程级的资源(如打开文件),但是各个线程拥有自己的栈空间。


进程和线程的关系.png

多线程的使用的好处:


实现多线程的常用方法:

class MyThread implements Runnable{
    public void run(){
        System.out.println("Thread body");
    }
}
public class Test{
    public static void main(String []args) {
        MyThread thread = new MyThread():
        Thread t = new Thread(thread);
        t.start();
    }
}

不管是通过继承Thread类还是通过使用Runnable接口实现多线程的方法,最终还是通过Thread的对象的API来控制线程的。

public class CallableAndFuture{
    //创建线程类
    public static class CallableTest implements Callable<String> {
          public String call() throws Exception{
               return "Hello world!"
          }
    }
    public static void main(String []args) {
        ExecutorService threaPool = Executor.newSingleThreadExecutor();
        //启动线程
        Future<String> future = threadPool.submit(new CallableTest());
        try{
            System.out.println("waiting thread to finish!");
             System.out.println(future.get());//等待线程结束,并获取返回结果
        }
    }
}

注:
一般推荐实现Runnable接口的方式,原因是:


run()方法与start()方法有什么区别
系统通过调用线程类的start()方法来启动一个线程,此时该线程处于就绪状态,而非运行状态,也就意味着这个线程可以被JVM来调度执行,在调度过程中,JVM通过调用线程类的run()方法来完成实际的操作做,当run()方法结束后,此线程就会终止。


多线程同步的实现方法

synchronized(syncObject){
    //访问syncObject的代码
}

线程的wait()、sleep()、join()、yeild()

上一篇 下一篇

猜你喜欢

热点阅读