多线程学习总结

本文介绍了Java中实现多线程的两种方式:继承Thread类和实现Runnable接口,并提供了示例代码。通过创建Thread子类对象和实现Runnable接口构建线程,展示了如何启动和控制线程执行。此外,还列举了Thread类的多个构造方法。
摘要由CSDN通过智能技术生成

多线程学习总结

一、多线程

多线程程序是指一个程序中包含多个执行流,它是实现并发机制的有效手段。从逻辑的观点看,多线程意味着一个程序的多个语句块同时执行,但不等于多次启动一个程序。
Java的多线程是一个类,这个类可以对它的线程进行控制,可以确定哪个线程的优先级高,哪个线程应该执行,等等。线程的执行由拥有这个线程的一个或多个类来控制。
Java中实现线程的方式有两种,第一种是生成Thread类的子类,并定义该子类自己的run()方法,线程要完成的任务在run()方法中实现。这种方法比较简单,但是如果定义的类已经是他类的子类,而Java不允许多重继承,我们可以采用第二种方法实现Runnable接口,通过实现Runnable接口中的run()方法来完成线程的任务。

二、构建Thread子类对象

public class Hello extends Thread{
    String threadId;
    public Hello(String threadId) {
        this.threadId = threadId;
    }
    public void run() {
        System.out.println("Thread started:" + this.threadId);
        for(int i = 0; i < 6; i++) {
            System.out.println("i=" + i + "\t");
        }
        System.out.println("Thread stopped:" + this.threadId);
    }
}
public class Test1 {
    public static void main(String[] args) {
        System.out.println("Starting Test1");
        Hello t1 = new Hello("thread1");
        t1.start();
        Hello t2 = new Hello("thread2");
        t2.start();
        Hello t3 = new Hello("thread3");
        t3.start();
        System.out.println("Test1 is done");
    }
}

三、用实现Runnable接口对象构建Thread

public class MyRunnable implements Runnable{
    String threadID;
    public MyRunnable(String threadID) {
        this.threadID = threadID;
    }
    public void run() {
        System.out.println("Thread started:" + this.threadID);
        for(int i = 0; i < 6; i++) {
            System.out.println("i=" + i + "\t");
        }
        System.out.println("Thread stopped:" + this.threadID);
    }
}
public class Test {
    public static void main(String[] args) {
        System.out.println("starting Test");
        Runnable r1 = new MyRunnable("thread1");
        Thread t1 = new Thread(r1);
        t1.start();
        Runnable r2 = new MyRunnable("thread2");
        Thread t2 = new Thread(r2);
        t2.start();
        Runnable r3 = new MyRunnable("thread3");
        Thread t3 = new Thread(r3);
        t3.start();
        System.out.println("Test is done");
    }
}

四、Thread类构造方法

Thread类有8个构造方法:
1.Thread()
2.Thread(Runnable target)
3.Thread(Runnable target, String name)
4.Thread(String name)
5.Thread(ThreadGroup group, Runnable target)
6.Thread(ThreadGroup group, Runnable target, String name)
7.Thread(ThreadGroup group, Runnable target, String name, long stackSize)
8.Thread(ThreadGroup group, String name)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值