Java多线程创建
-java.lang.Thread
线程继承Thread类,通过start方法来启动线程实现run方法
public class TextRead extends Thread{
public void run() {
System.out.println(“hello”);
}
public static void main(String[] args) throws Exception{
new TextRead().start();
}
}
-java.lang.Runnable接口
线程实现Runnable接口,通过start方法实现run方法
实现Runnable的类必须包装在Thread类里面,才可以启动
public class TextRead implements Runnable{
public void run() {
System.out.println(“hello”);
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
new Thread(new TextRead()).start();
}
}
java 多线程启动
1、start方法,会自动以新进程调用run方法
2、直接调用run方法,将变成串行执行
3、同一个线程,多次start会报错,只执行第一次start方法
4、多个线程启动,其启动的先后顺序是随机的
5、线程无需关闭,只要其run方法执行结束后,自动关闭
6、main韩式可能早于新线程结束,整个程序并不终止
7、整个程序终止是等所有的线程都终止(包括main函数线程)
——————————————————————————
public class TextRead {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
new Test0().run();
while(true) {
System.out.println(“main is running”);
Thread.sleep(10);
}
}
}
class Test0{
public void run() {
System.out.println(“test is running”);
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
——————————————————————————————————
public class TextRead {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
new Test0().start();
while(true) {
System.out.println(“main is running”);
Thread.sleep(10);
}
}
}
class Test0 extends Thread{
public void run() {
System.out.println(“test is running”);
try {
Thread.sleep(10);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
调用run方法来启动run方法,将会是串行运行
调用start方法,来启动run方法,将会是并行运行(多线程运行)
——————————————————————————————
public class TextRead {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//Runnable对象必须放在一个Thread类中才能实现
//创建Thread类的一个实例
Test tt = new Test();
//创建一个Thread实例
Thread t = new Thread(tt);
//使线程进入Runnable状态
t.start();
while(true) {
System.out.println(“main is running”);
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Test implements Runnable{
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName()+“is running”);
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
1、main韩式可能早于新线程结束,整个程序并不终止
2、整个程序终止是等所有的线程都终止(包括main函数线程)
本文介绍Java中创建和启动多线程的两种主要方式:继承Thread类和实现Runnable接口。通过具体代码示例展示了如何正确使用这两种方法,并解释了它们之间的区别。此外还讨论了线程的启动机制及注意事项。
1004

被折叠的 条评论
为什么被折叠?



