- 操作线程的方法操作线程有很多方法,这些方法可以使线程从某一种状态过渡到另一种状态。
- 线程的休眠能控制线程行为的方法之一是调用sleep()方法,sleep()方法可以指定线程休眠的时间,线程休眠的时间以毫秒为单位。线程的休眠 实例:
public class Demo2 {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(i);
try {
Thread.sleep(200);// 线程休眠(单位:毫秒)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 线程的加入 假如当前程序为多线程程序,并且存在一个线程A,现在需要插入线程B,并要求线程B执行完毕后,再继续执行线程A,此时可以使用 Thread类 中的 join()方法 来实现。当某个线程使用 join()方法 加入到另外一个线程时,另一个线程会等待该线程执行完毕后 再继续执行。线程的加入 实例:
import javax.swing.*;
import java.awt.*;
public class Demo3 extends JFrame {
private Thread threadA;
private Thread threadB;
final JProgressBar progressBar = new JProgressBar();
final JProgressBar progressBar2 = new JProgressBar();
public static void main(String[] args) {
new Demo3();
}
public Demo3(){
super();
setSize(100,100);
setVisible(true);
getContentPane().add(progressBar, BorderLayout.NORTH);
getContentPane().add(progressBar2, BorderLayout.SOUTH);
progressBar.setStringPainted(true);
progressBar2.setStringPainted(true);
threadA = new Thread(new Runnable() {
int count=0;
@Override
public void run() {
while (true){
progressBar.setValue(++count);
try {
Thread.sleep(100);
if (count==20){
threadB.join();// 线程B加入到线程A中
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
threadA.start();
threadB = new Thread(new Runnable() {
int count=0;
@Override
public void run() {
while (true){
progressBar2.setValue(++count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count==100){
break;
}
}
}
});
threadB.start();
}
}
- 线程的中断当线程使用了 sleep()方法 、wait()方法 进入了 就绪状态,可以使用 Thread类 中的 interrupt()方法 使线程 离开 run()方法,同时 结束线程。线程的中断 实例:
import javax.swing.*;
import java.awt.*;
public class Demo4 extends JFrame {
Thread thread;
public Demo4() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200, 100);
setVisible(true);
final JProgressBar jProgressBar = new JProgressBar();
getContentPane().add(jProgressBar, BorderLayout.NORTH);
jProgressBar.setStringPainted(true);
thread = new Thread() {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
jProgressBar.setValue(i);
if (i == 50) {
this.interrupt();// 中断线程
}
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("123");
}
}
};
thread.start();
}
public static void main(String[] args) {
new Demo4();
}
}
Original: https://www.cnblogs.com/TeaTracing/p/16132999.html
Author: TeaTracing
Title: 操作线程的方法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/621910/
转载文章受原作者版权保护。转载请注明原作者出处!