多线程常用操作方法:
1:线程的命名与取得
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) throws Exception {
MyThread mt = new MyThread() ;
new Thread(mt,"线程A").start() ; // 设置了线程的名字
new Thread(mt).start() ; // 未设置线程名字
new Thread(mt).start() ; // 未设置线程名字
new Thread(mt).start() ; // 未设置线程名字
new Thread(mt).start() ; // 未设置线程名字
new Thread(mt,"线程B").start() ; // 设置了线程的名字
}
}
//运行结果:
线程A
Thread-3
线程B
Thread-2
Thread-1
Thread-0
2:观察下面程序
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) throws Exception {
MyThread mt = new MyThread() ;
new Thread(mt,"线程对象").start() ; // 设置了线程的名字
mt.run(); // 对象直接调用run()方法
}
}
//运行结果
main
线程对象
上述的截图是只是在主方法中执行了一些代码。然后就启动了一个JVM进程。
3:主线程分为若干个子线程
在任何的开发之中,主线程可以创建若干个子线程,创建子线程的目的是可以将一些复杂逻辑或比较耗时的逻辑交由子线程处理:
public class Test {
public static void main(String[] args) throws Exception {
System.out.println("1、执行操作任务一。");
int temp = 0 ;
for (int x = 0 ; x < Integer.MAX_VALUE ; x ++) {
temp += x ;
}
System.out.println("2、执行操作任务二。");
System.out.println("n、执行操作任务N。");
}
}
//执行结果
1、执行操作任务一。
2、执行操作任务二。
n、执行操作任务N。
上述代码的执行效果:在第一条语句执行输出“1、执行操作任务一。”后,会停顿以下,再执行后续的代码。
耗时的操作不应该再程序的主体之中;应该启动一个子线程,那么主线程执行就会很快,子线程去耗时。
public class Test {
public static void main(String[] args) throws Exception {
System.out.println("1、执行操作任务一。");
new Thread(()->{ // 子线程负责统计
int temp = 0 ;
for (int x = 0 ; x < Integer.MAX_VALUE ; x ++) {
temp += x ;
}
}).start();
System.out.println("2、执行操作任务二。");
System.out.println("n、执行操作任务N。");
}
}
实际开发之中就是主线程负责流程的控制,而子线程负责耗时操作。
就像微博上的操作,一个线程负责刷新,一个线程负责呈现微博内容供观看;刷新不会影响浏览。