Java程序设计:Java Thread实验

目录

1 实验名称

2 实验目的

3 实验源代码

4 实验运行结果图

5 总结


1 实验名称

      Java Thread实验

2 实验目的

       继续熟练掌握在eclipse中调试代码

       掌握Java 多线程中的基本概念及使用方法

       掌握在GUI中使用Thread的子类创建线程

3 实验源代码

Application.java:

public class Application {
    public static void main(String[] args) {//默认主线程
        //创建一个子线程对象
        MyThread myThread = new MyThread();
        //开启子线程类
        myThread.start();

        Thread thread = new Thread(new MyThreadTarget());
        thread.start();
        //开启新线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Thread.sleep(1000);
                        System.out.println("lll音乐播放·~~");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        int i = 0;  //    ^---^
        try {      //表情 /'-=-'\
            while (true) {
                i++;
                System.out.println("主线程:" + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

MyThread.java:

class MyThread extends Thread {
    public void run(){
    int i=0;
    try {
       while(true) {
           i++;
           System.out.println("子线程a:" + i);
           Thread.sleep(500);
       }
    }catch(InterruptedException e) {
        throw new RuntimeException(e);
    }
    }
}

MyThreadTarget.java:

class MyThreadTarget extends Thread {
    public void run(){
        int i=0;
        try {
            while(true) {
                i++;
                System.out.println("子线程b:" + i);
                Thread.sleep(500);
            }
        }catch(InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

4 实验运行结果图

5 总结

       线程是比进程更小的执行单位。一个进程在其执行过程中,可以产生多个线程,形成多条执行线索,每条线索,即每个线程也有它自身的产生、存在和消亡的过程,也是一个动态的概念。当Java程序包含图形用户界面(GUI)时,java虚拟机在运行应用程序时自动启动更多的线程。用Thread子类创建线程的优点是:可以在子类中增加新的成员变量,使线程具有某种属性,也可以在子类中新增加方法,使线程具有某种功能,但是java不支持多继承,Thread类的子类不能再扩展其他的类。注意的是,在编写Thread类的子类时需要重写父类的run方法,其目的是规定线程的具体操作,否则线程就什么也不做,因为父类的run方法中没有任何操作语句。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茜茜西西CeCe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值