码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程1:进程与线程概述

时间:2016-04-16 15:15:09      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

进程和线程
首先介绍下进程和线程
进程
进程就是执行中的程序,程序是静态的概念,进程是动态的概念。
线程
进程中独立运行的子任务就是一个线程。像QQ.exe运行的时候就有很多子任务在运行,比如聊天线程、好友视频线程、下载文件线程等等。
多线程
多线程则指的是在单个程序中可以同时运行多个不同的线程执行不同的任务.
• 多线程编程的目的,就是"最大限度地利用CPU资源",当某一线程的处理不需要占用CPU而只和I/O等资源打交道时,让需要占用CPU资源的其它线程有机会获得CPU资源。从根本上说,这就是多线程编程的最终目的。、
• 多线程可帮助你编写出CPU最大利用率的高效程序,使得空闲时间保持最低。这对Java运行的交互式的网络互连环境是至关重要的,因为空闲时间是公共的。例如,网络的数据传输速率远低于计算机处理能力,而本地文件系统资源的读写速度也远低于CPU的处理能力。当然,用户输入也比计算机慢很多。在传统的单线程环境中,程序
必须等待每一个这样的任务完成以后才能执行下一步—尽管CPU有很多空闲时间。多线程使你能够获得并充分利用这些空闲时间。
• 一个进程可以包含一个或多个线程
• 一个程序实现多个代码同时交替运行就需要产生多个线程
• CPU随机的抽出时间,让我们的程序一会做这件事情,一会做另外一件事情
线程与进程的区别
• 多个进程的内部数据和状态都是完全独立的,而多线程是共享一块内存空间和一组系统资源,有可能互相影响.
• 线程本身的数据通常只有寄存器数据,以及一个程序执行时使用的堆栈, 所以线程的切换比进程切换的负担要小。

创建线程的方式

线程的实现有两种方式,第一种方式是继承 Thread 类,然后重写 run 方法;第二种是实现 Runnable 接口,然后实现其 run 方法。
将我们希望线程执行的代码放到 run 方法中,然后通过 start 方法来启动线程, start方法首先为线程的执行准备好系统资源,然后再去调用 run 方法。 当某个类继承了Thread 类之后,该类就叫做一个线程类。

1、继承Thread,重写父类的run()方法。

public class ThreadTest {
    public static void main(String[] args) {
        MyThread1 t1 = new MyThread1("Thread1");
        MyThread2 t2 = new MyThread2("Thread2");
        t1.start();
        t2.start();
    }
}

class MyThread1 extends Thread {

    public MyThread1(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " is running");
        }
    }
}

class MyThread2 extends Thread {

    public MyThread2(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " is running");
        }
    }
}

运行结果

.........................
Thread2 is running
Thread1 is running
Thread1 is running
Thread2 is running
Thread2 is running
Thread2 is running
Thread1 is running
Thread2 is running
Thread2 is running
Thread1 is running
Thread2 is running
Thread2 is running
Thread1 is running
Thread1 is running
Thread2 is running
Thread2 is running
Thread2 is running
Thread2 is running
Thread2 is running
..........................

可以看到,线程1和线程2交替运行。

对于单核 CPU 来说,某一时刻只能有一个线程在执行( 微观串行),从宏观角度来看,多个线程在同时执行( 宏观并行)。
对于双核或双核以上的 CPU 来说,可以真正做到微观并行。
2、实现Runnable接口。和继承自Thread类差不多,不过实现Runnable后,还是要通过一个Thread来启动,因为Runnable接口中只有一个run方法

public class ThreadTest2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyThread1());
        Thread t2 = new Thread(new MyThread2());
        t1.start();
        t2.start();
    }
}

class MyThread1 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " is running");
        }
    }
}

class MyThread2 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " is running");
        }
    }
}

运行结果

...........................
Thread-0 is running
Thread-1 is running
Thread-1 is running
Thread-0 is running
Thread-1 is running
Thread-0 is running
Thread-1 is running
Thread-0 is running
Thread-1 is running
Thread-0 is running
...........................

还记得匿名内部类吗

public class ThreadTest2 {
    public static void main(String[] args) {
        
        //参数是实现了Runnable接口的类的一个实例
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + " is running");
                }
            }
        });

        thread.start();
    }
}

两种多线程实现方式的对比

public class Thread implements Runnable {
}

可以看出Thread类实现了Runnable接口,因此实现了 Runnable 接口中的 run 方法;

private Runnable target;
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

线程是由操作系统来执行的,所以有一些本地的native方法。
看一下两个重要的构造方法

public Thread() {
    init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

当生成一个线程对象时,如果没有为其设定名字,那么线程对象的名字将使用如下形式: Thread-number,该 number 将是自动增加的,并被所有的 Thread 对象所共享( 因为它是 static 的成员变量)。

启用线程的唯一方法是调用start方法。

/**
 * Causes this thread to begin execution; the Java Virtual Machine
 * calls the run method of this thread.
 * The result is that two threads are running concurrently: the
 * current thread (which returns from the call to the
 * start method) and the other thread (which executes its run method).
 * It is never legal to start a thread more than once.
 * In particular, a thread may not be restarted once it has completed execution.*/
public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
.................
start0(); } private native void start0();

--当使用第一种方式来生成线程对象时,我们需要重写 run 方法,因为 Thread 类的 run方法此时什么事情也不做。
--当使用第二种方式来生成线程对象时,我们需要实现 Runnable 接口的 run 方法,然后使用 new Thread(new MyThread())( 假如 MyThread 已经实现了 Runnable 接口) 来生成线程对象,这时的线程对象的 run 方法就会调用 MyThread 类的 run 方法,这样我们自己编写的 run 方法就执行了。

停止线程的方式
不能调用stop方法来停止线程
推荐使用

public class ControlThread {

    private MyThread runnable = new MyThread();

    private Thread thread = new Thread(runnable);

    public void startThread() {
        thread.start();
    }

    public void stopThread() {
        runnable.stopRunning();
    }

}

class MyThread implements Runnable {

    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            //TODO
        }
    }

    public void stopRunning() {
        flag = false;
    }
}

 

 
















































































 

Java多线程1:进程与线程概述

标签:

原文地址:http://www.cnblogs.com/winner-0715/p/5398303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!