创建多线程笔记

来源:互联网 发布:c51单片机流水灯程序 编辑:程序博客网 时间:2024/06/08 04:38

最近在看线程,所以总结一下。

一:创建线程的两种方法

1.继承Thread类 

2.实现Runnable方法

两者而言,实现Runnable方法更好,因为java是单继承,多实现的。

二:继承Thread类,一个简单的多线程

public class MyThread extends Thread{
private String name;
public MyThread(String name){
super(name);
//this.name = name;
}
public void run(){
//写自己的代码
System.out.println("hello"+getName());
}


}


//测试类

package com.briup.thread;

public class ThreadTest {

public static void main(String[] args) {
MyThread t1 = new MyThread("线程一");
MyThread t2 = new MyThread("线程二");
/*t1.setName("线程一");
t2.setName("线程二");*/
t1.start();   //thread-0
t2.start();  //thread-1
}
}

三:实现Runnable方法

package com.briup.thread;

public class MyThread extends Thread{
private String name;
public MyThread(String name){
super(name);
//this.name = name;
}
public void run(){
//写自己的代码
System.out.println("hello"+getName());
}
}


//测试类

package com.briup.thread;
public class ThreadTest {
public static void main(String[] args) {
MySecondThread mst = new MySecondThread();
Thread t3 = new Thread(mst);
Thread t4 = new Thread(mst);
t3.start();
t4.start();
}


}


四:start()方法和run()方法的区别

如果我们自己调用了run()方法,则是普通的方法,如果我们调用start()方法,则是jvm调用了run()方法

1.为什么要执行run()方法

是为了区分哪些代码要运行在子线程当中。子线程执行耗时的代码