javaCreateRunMultiThread - juedaiyuer/researchNote GitHub Wiki
#java多线程笔记#
##多线程##
java.lang
- class thread
- interface runnable
##创建线程##
###继承Thread类覆盖run方法###
package test;
public class testMultiThread {
public static void main(String[] args){
Demo d = new Demo();
d.start();
for(int i=0;i<60;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
class Demo extends Thread{
public void run(){
for(int i=0;i<60;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
- 如果我们的类已经从一个类继承,则无法再继承Thread类
###实现Runnable接口###
public class ThreadDemo2 {
public static void main(String[] args){
Demo2 d =new Demo2();
Thread t = new Thread(d);
t.start();
for(int x=0;x<60;x++){
System.out.println(Thread.currentThread().getName()+x);
}
}
}
class Demo2 implements Runnable{
public void run(){
for(int x=0;x<60;x++){
System.out.println(Thread.currentThread().getName()+x);
}
}
}
- 实现Runnable接口方式,比较通用
- 为了使线程能够执行run()方法,需要在Thread类的构造函数中传入Demo2的实例对象
##线程名##
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable, "New Thread");
thread.start();
#需要注意的是,因为MyRunnable并非Thread的子类,所以MyRunnable类并没有getName()方法
System.out.println(thread.currentThread().getName());
##线程休眠##
#静态方法
Thread.sleep(long millis)
Thread.sleep(long millis, int nanos)
##source##