您的位置:首页 > 编程语言 > Java开发

多线程_JAVA

2016-06-29 21:33 344 查看

多线程在java中的两种实现方法

1.继承Thread类(不推荐使用)

因为java只支持单一继承,,,若一个类已经继承了一个类就不能再次继承Thread

1.创建类继承到Thread

class MyThread extends Thread(){
//重写run()方法
public void run() {
System.out.println("这里是多线程");
}
}


2.创建测试类

public class Test {
public static void main(String[] args) {

//一个对象就是一个线程
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
m.start();
}
}


首先调用start()方法,如果先调用run()方法,就相当于普通类执行了一个普通run()方法,否则就没有了多线程的性质了

可以理解为调用start()方法后,自动执行run方法。

2.实现Runnable接口(主要使用)

1.创建一个类实现Runnable接口,重写run方法

public class Thread_1 implements Runnable {
public void run() {
int i=1;
while(i<20){
System.out.println(Thread.currentThread().getName()+"----is  running--");
i++;
}
}
}


Thread.currentThread():获得当前线程实例对象

2.创建测试类

public class Test {
public static void main(String[] args) {
//实例化Thread_1
Thread_1 t=new Thread_1();
//将Thread_1的对象作为参数传入,第二个参数为线程名字
Thread t1=new Thread(t,"线程001");
Thread t2=new Thread(t,"线程002");
t1.start();
t2.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: