Java多线程创建
- java.lang.Thread
– 线程继承Thread类,实现run方法 - java.lang.Runnable接口
– 线程实现Runnable接口,实现run方法
Java多线程启动
- 启动
– 调用start方法,会自动以新进程调用run方法
– 直接调用run方法,将变成串行执行
– 同一个线程,多次start会报错,只执行第一次start方法
– 多个线程启动,其启动的先后顺序是随机的
– 线程无需关闭,只有其run方法执行结束后,自动关闭
– main函数(主线程)可能早于新线程结束,整个程序并不终止
– 整个程序终止是等所有的线程都终止(包括main函数线程)
JNI,Java Native Interface,它提供了若干个API,可以使得Java程序调用C/C++程序
Thread 与 Runnable实现对比
- 因为一个类只能继承一个父类,但可以继承多个接口,所以建议使用Runnable接口,这样会节省父类的名额
- Thread类实现Runnable
- Runnable启动时需要Thread了的支持
- Runnable更容易实现多线程中资源共享
- Thread里面,必须用static变量,才能实现变量共享,在Runnable里面可以使用普通的变量就可以实现变量共享
- 结论:建议实现Runnable接口来完成多线程
Java的四个主要接口:Clonable,用于对象克隆; Comparable,用于对象比较;Serializable,用于对象序列化;Runnable,用于对象线程化
实例一:run\start方法的区别
1 调用run方法,来启动run方法,将会是串行运行
2 调用start方法,来启动run方法,将会是并行运行(多线程运行)
package com.torey;
/**
* @ClassName:ThreadDemo0
* @Description:
* @author: Torey
*/
public class ThreadDemo0 {
public static void main(String[] args) throws InterruptedException {
/*
* 1 调用run方法,来启动run方法,将会是串行运行
* 2 调用start方法,来启动run方法,将会是并行运行(多线程运行)
* */
TestThread1 testThread1=new TestThread1();
new Thread(testThread1).start();
new Thread(testThread1).run();
while (true){
System.out.println("main thread is running");
Thread.sleep(1000);
}
}
}
class TestThread1 implements Runnable{
public void run() {
while (true){
System.out.println("TestThread1 is running"+Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
实例二:mian线程和子线程都结束了,整个程序才算终止
1 main线程可能早于子线程结束
2 mian线程和子线程都结束了,整个程序才算终止。
package com.torey;
/**
* @ClassName:ThreadDemo2
* @Description:
* @author: Torey
*/
public class ThreadDemo2 {
/*
1 main线程可能早于子线程结束
2 mian线程和子线程都结束了,整个程序才算终止。
*/
public static void main(String[] args) throws InterruptedException {
new TestThread2().start();
System.out.println("主线程结束");
}
}
class TestThread2 extends Thread{
@Override
public void run(){
while (true) {
System.out.println("TestThread2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
一个线程不能多次start,多次start将报异常;
package com.torey;
/**
* @ClassName:ThreadDemo4
* @Description:
* @author: Torey
*/
public class ThreadDemo4 {
public static void main(String[] args){
/*
1 一个线程不能多次start,多次start将报异常;
2 多个线程对象都start后,哪一个先执行,完全由JVM/操作系统来主导,程序员无法指定
*/
TestThread4 t = new TestThread4();
t.start();
// 这里会报错,再次执行会报错
t.start();
//
TestThread4 t1 = new TestThread4();
t1.start();
TestThread4 t2 = new TestThread4();
t2.start();
}
}
class TestThread4 extends Thread{
@Override
public void run() {
System.out.println("TestThread4 run,id=" + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}