一、多线程使用
1.1 使用方式
- 继承Thread类
- 实现Runnable接口
1.2 继承Thread类
public class MyThread extends Thread{
@Override
public void run()
{
super.run();
System.out.println("MyThread");
}
}
public class Run {
public static void main(String args[])
{
MyThread mythread = new MyThread();
mythread.start();
System.out.println("Program Exits");
}
}
Output:
Program Exits
MyThread
Tip: 上例可以显示线程调用的随机性
public class MyThread extends Thread{
@Override
public void 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)
{
e.printStackTrace();
}
}
}
public class Test {
public static void main(String args[])
{
try
{
MyThread thread = new MyThread();
thread.setName("myThread");
thread.start();
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)
{
e.printStackTrace();
}
}
}
Output:
run=main
run=myThread
run=myThread
run=main
run=main
run=myThread
run=main
run=main
run=myThread
run=main
run=myThread
run=main
run=main
run=main
run=myThread
run=main
run=myThread
run=myThread
run=myThread
run=myThread
Tip:
- Thread.start()方法通知“线程规划器”此线程已经准备就绪,等待被调用线程对象的run()方法
- 如果thread.run()是同步的,则此线程对象并不交给“线程规划器”,而是由main主线程来调用run()方法。
1.3 实现Runnable接口
如果欲创建的线程类已经有一个父类,这时候就不能再继承Thread类,必须实现Runable接口。
-
参考书籍
《Java 多线程编程核心技术》高洪岩著;北京:机械工业出版社.2017.5