使用多线程
学习一项技术就要去使用它
package test;
public class Test {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
}
main
如上就是输出了一个叫main的线程,而跟main方法名没有关系。
继承Thread类
package com.mythread.www;
public class MyThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("MyThread");
}
}
运行类如下:
package com.mythread.www.thread;
import com.mythread.www.MyThread;
public class Run {
public static void main(String[] args) {
MyThread mythread=new MyThread();
mythread.start();
System.out.println("运行结束");
}
}
运行结束
MyThread
从运行结果来看,run中的执行方法比较晚,这也就是说运行结果与代码顺序无关。
线程是一个子任务,CPU不确定的方法,或者说是以随机的时间来调用线程的方法run
创建自定义线程
package mythread;
public class MyThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
for (int i = 0; i < 10; i++) {
int time = (int) (Math.random() * 1000);
Thread.sleep(time);
System.out.println("run="+Thread.currentThread().getName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行类:
package test;
import mythread.MyThread;
public class Test2 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.setName("myThread");
thread.start();
for (int i = 0; i <10; i++) {
int time=(int)(Math.random()*1000);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("main="+Thread.currentThread().getName());
}
}
}
main=main
run=myThread
main=main
run=myThread
main=main
run=myThread
main=main
main=main
run=myThread
run=myThread
run=myThread
main=main
main=main
run=myThread
main=main
run=myThread
main=main
run=myThread
main=main
run=myThread
Thread.java类中的start()方法通知“线程规划器”此线程已经准备就绪,等待调用,等待调用线程对象的run()方法。这个过程其实就是让系统安排一个时间来调用Thread中的run()方法,也就是使线程得到运行,启动线程,具有异步执行的结果。如果调用代码thread.run()就不是异步执行了,而是同步,那么此线程对象并不交给“线程规划器”来处理,而是由main主线程来调用run()方法,也就是必须等run()方法中的代码执行完才可以执行后面的代码。