多线程作为Java中的第一大特色,肯定需要仔细斟酌一番。
(一)了解什么是进程与线程
进程:程序在操作系统中的一次进程;
线程:进程中的一个分支;
(二)实现多线程的四种方式:
1、继承Thread 类实现多进程
首先继承Thread类;再覆写run();最后调用start()启动多线程。
关于覆写run():run()为多线程的核心方法,相当于主线程中的main(),为每个线程的入口,其包含具体的线程实现逻 辑。
- 一个线程只能调用一次start(),否则抛出异常;
- native 声明的方法没有方法体,只有方法声明,但本地方法不是抽象方法而是Java调用C语言的方法;
- run()是由JVM 创建完本地操作系统后回调的方法,不可手工调用,否则就是普通方法;
class myThread extends Thread {
private String title;
public myThread(String title) {
super();
this.title = title;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.title+" "+i);
}
}
}
public class Test {
public static void main(String[] args) {
myThread thread =new myThread("A");
myThread thread2 =new myThread("B");
myThread thread3 =new myThread("C");
thread.start();
thread2.start();
thread3.start();
}
}
2、覆写Runnable 接口实现多线程
首先覆写Runnable 接口;再覆写run();使用Thread 的start()启动多线程
- 当子类实现Runnable 接口,此时的子类与Thread 的角色就是典型的代理设计模式。子类负责正是业务操作,Thread 负责资源调度和创建线程辅助真实业务;
- 继承Thread 类与 覆写Runnable 接口的区别:
a.实现Runnable 接口可以避免单继承局限;
b.实现Runnable 接口可以更好的体现程序共享资源的概念。
class myThread implements Runnable {
private String title;
public myThread(String title) {
super();
this.title = title;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.title+" "+i);
}
}
}
public class Test {
public static void main(String[] args) {
Runnable runnable=new myThread("A");
Runnable runnable1=new myThread("B");
Runnable runnable2=new myThread("C");
new Thread(runnable).start();
new Thread(runnable1).start();
new Thread(runnable2).start();
}
}
3、覆写 callable 实现多线程
首先覆写callable 接口;再覆写call();使用Thread 的start()启动多线程
- 核心方法是call();
- 具有返回值;
class myThread implements Callable<String> {
private int ticket=10;
@Override
public String call() throws Exception {
while(ticket>0) {
System.out.println("剩余"+this.ticket+"张票");
ticket--;
}
return "卖完啦....";
}
}
public class Test {
public static void main(String[] args) {
Callable<String> callable=new myThread();
FutureTask<String> futureTask=new FutureTask<>(callable);
Thread thread1=new Thread(futureTask);
Thread thread2=new Thread(futureTask);
Thread thread3=new Thread(futureTask);
thread1.start();
thread2.start();
thread3.start();
}
}
4、线程池(之后更新。。。)