第18章 多线程----线程的生命周期

线程具有生命周期,其中包含7中状态,分别为:出生状态、就绪状态、运行状态、等待状态、休眠状态、阻塞状态、死忙状态。

1、线程的休眠

例如:在项目中创建SleepMethodTest类,该类继承了JFrame类,实现在窗体中自动画线段的功能,并且为线段设置颜色,颜色是随机产生的。

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class SleepMethodTest extends JFrame { private static final long serialVersionUID = 1L; private Thread t; private static Color[] color = { Color.BLACK, Color.BLUE, Color.CYAN, //定义颜色数组 Color.GREEN, Color.ORANGE, Color.YELLOW, Color.RED, Color.PINK, Color.LIGHT_GRAY }; private static final Random rand = new Random();// 创建随机对象 private static Color getC() {// 获取随机颜色值的方法 return color[rand.nextInt(color.length)]; } public SleepMethodTest() { t = new Thread(new Runnable() {// 创建匿名线程对象 int x = 30;// 定义初始坐标 int y = 50; public void run() {// 覆盖线程接口方法 while (true) {// 无限循环 try { Thread.sleep(100);// 线程休眠0.1秒 } catch (InterruptedException e) { e.printStackTrace(); } // 获取组件绘图上下文对象 Graphics graphics = getGraphics(); graphics.setColor(getC());// 设置绘图颜色 // 绘制直线并递增垂直坐标 graphics.drawLine(x, y, 100, y++); if (y >= 80) { y = 50; } } } }); t.start();// 启动线程 } public static void main(String[] args) { init(new SleepMethodTest(), 100, 100); } // 初始化程序界面的方法 public static void init(JFrame frame, int width, int height) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(width, height); frame.setVisible(true); } }

2、线程的加入

如果当前某程序为多线程程序,假如存在一个线程A,现在需要插入线程B,并要求线程B先执行完毕,然后再继续执行线程A,此时可以使用Thread类中的join()方法来完成。

例如:在项目中创建JoinTest类,该类继承了JFrame类。该实例包括两个进度条,进度条的进度由线程来控制,通过使用join()方法使上面的进度条必须等待下面的进度条完成后才可以继续。

import java.awt.*;
import javax.swing.*;

public class JoinTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private Thread threadA; // 定义两个线程
    private Thread threadB;
    final JProgressBar progressBar = new JProgressBar(); // 定义两个进度条组件
    final JProgressBar progressBar2 = new JProgressBar();
    int count = 0;
    
    public static void main(String[] args) {
        init(new JoinTest(), 100, 100);
    }
    
    public JoinTest() {
        super();
        // 将进度条设置在窗体最北面
        getContentPane().add(progressBar, BorderLayout.NORTH);
        // 将进度条设置在窗体最南面
        getContentPane().add(progressBar2, BorderLayout.SOUTH);
        progressBar.setStringPainted(true); // 设置进度条显示数字字符
        progressBar2.setStringPainted(true);
        // 使用匿名内部类形式初始化Thread实例子
        threadA = new Thread(new Runnable() {
            int count = 0;
            
            public void run() { // 重写run()方法
                while (true) {
                    progressBar.setValue(++count); // 设置进度条的当前值
                    try {
                        Thread.sleep(100); // 使线程A休眠100毫秒
                        threadB.join(); // 使线程B调用join()方法
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        threadA.start(); // 启动线程A
        threadB = new Thread(new Runnable() {
            int count = 0;
            
            public void run() {
                while (true) {
                    progressBar2.setValue(++count); // 设置进度条的当前值
                    try {
                        Thread.sleep(100); // 使线程B休眠100毫秒
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (count == 100) // 当count变量增长为100时
                        break; // 跳出循环
                }
            }
        });
        threadB.start(); // 启动线程B
    }
    
    // 设置窗体各种属性方法
    public static void init(JFrame frame, int width, int height) {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }
}

3、线程的中断

以往有的时候会使用stop()方法停止线程,但现在版本的JDK早已废除了stop()方法,不建议使用stop()方法来停止一个线程的运行,现在提倡在run()方法中使用无限循环的形式,然后使用一个布尔型标记控制循环的停止。

例如:在项目中创建InterruptedSwing()方法,该类实现了Runnable接口,创建一个进度条,在表示进度条的线程中使用interrupted()方法。

import java.awt.*;
import javax.swing.*;

public class InterruptedSwing extends JFrame {
    private static final long serialVersionUID = 1L;
    Thread thread;
    
    public static void main(String[] args) {
        init(new InterruptedSwing(), 100, 100);
    }
    
    public InterruptedSwing() {
        super();
        final JProgressBar progressBar = new JProgressBar(); // 创建进度条
        getContentPane().add(progressBar, BorderLayout.NORTH);  //将进度条放置在窗体合适的位置
        progressBar.setStringPainted(true); // 设置进度条上显示数字
        thread = new Thread(new Runnable() {
            int count = 0;
            
            public void run() {
                while (true) {
                    progressBar.setValue(++count); // 设置进度条的当前值
                    try {
                        Thread.sleep(1000); // 使线程休眠1000豪秒
                        // 捕捉InterruptedException异常
                    } catch (InterruptedException e) {
                        System.out.println("当前线程序被中断");
                        break;
                    }
                }
            }
        });
        thread.start(); // 启动线程
        thread.interrupt(); // 中断线程
    }
    
    public static void init(JFrame frame, int width, int height) {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }
    
}

 

转载于:https://www.cnblogs.com/chamie/p/4713590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值