赞
踩
多线程:允许"同时"执行多段代码。实际上多线程是并发运行的,每段代码都是走走停停的。CPU会在这些线程间快速切换,保证每段代码都有进度。从而感官上是同时运行。
线程的创建:
第一种创建方式:定义一个线程类并继承线程Thread,然后重写run方法。run方法定义线程执行的任务代码。
- package thread;
- public class ThreadDemo {
- public static void main(String[] args) {
- Thread t1=new MyThread1();
- Thread t2=new MyThread2();
- /**启动线程要执行start方法,而不是直接调用run方法 */
- t1.start();
- t2.start();
- }
- }
- class MyThread1 extends Thread{
- public void run() {
- for (int i =0;i<1000;i++) {
- System.out.println(" ");
- }
- }
- }
- class MyThread2 extends Thread{
- public void run() {
- for (int i =0;i<1000;i++) {
- System.out.println(".");
- }
- }
- }

第一种创建线程的方式的不足:
1.java是单继承,导致了无法再继承其他类来实现代码复用,不利于开发。
2.由于在线程内部直接重写run方法定义了线程要执行的任务,导致该线程只能执行该任务,使得线程与任务存在必然的强耦合关系,复用性变差。
第二种创建方式:
实现Runnable接口单独定义线程任务。
- package thread;
- public class ThreadDemo2{
- public static void main(String[] args){
- Runnable r1=new MyRunnable1();
- Runnable r2=new MyRunnable2();
- Thread t1=new Thread(r1);
- Thread t2=new Thread(r2);
- t1.start();
- t2.start();
- }
- }
- class MyRunnable1 implements Runnable{
- public void run() {
- for (int i =0;i<1000;i++) {
- System.out.println(00);
- }
- }
- }
- class MyRunnable2 implements Runnable{
- public void run() {
- for (int i =0;i<1000;i++) {
- System.out.println(111111);
- }
- }
- }

也可以使用匿名内部类的方式完成两种线程的创建:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。