多线程

来源:互联网 发布:淘宝卖家怎么设置会员 编辑:程序博客网 时间:2024/05/21 10:07

多线程

在我们的OS里,

进程是资源分配的最小单位

线程是cpu调度的最小单位

1、继承Thread

   创建:  A extends Thread

   在A中实现run()

   启动:利用继承自Thread strart() 方法

          A a = new A();

  a.start();

2、实现Runnable接口

   创建:  A implements Runnable

   在A中实现run()

   启动: 以A的对象为Thread的构造函数的参数创建Thread对象

   并且利用它的start()方法调度启动线程

          A a = new A();

  Thread b = new Thread(a);

  b.start();

3、利用Timer TimerTask

    创建:创建TimerTask的子类,并实现run()方法得到时钟器任务类

          MyTimerTask extends TimerTask{

public void run(){

}

  }

    启动:创建时钟器Timer对象

          利用时钟器对象的schedule()方法启动线程任务

  Timer timer = new Timer();

  timer.schedule(new MyTimerTask(), ....,...);

3种方法实现多线程:

import java.util.Timer;

import java.util.TimerTask;

public class MyFirstThreadTest {

public static void main(String[] args) {

// TODO Auto-generated method stub

// MyThread1 mt = new MyThread1();

// mt.start();

// MyThread2 mt2 = new MyThread2();

// Thread t = new Thread(mt2);

MyThread3 mt3 = new MyThread3();

Timer timer = new Timer();

timer.schedule(mt3, 3000,500);

for(int i=0;i<10;i++){

System.out.println("Good Morning!!");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class MyThread1 extends Thread{

public void run(){

for(int i=0;i<10;i++){

System.out.println("Hello world");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class MyThread2 implements Runnable{

public void run() {

for(int i=0;i<10;i++){

System.out.println("Hello world");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class MyThread3 extends TimerTask{

public void run() {

for(int i=0;i<10;i++){

System.out.println("Hello world");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

原创粉丝点击