11.2Java多线程之新建线程

多线程的创建:
方法一:

public class Main {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start(); // 启动新线程
    }
}
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}

创建Thread对象,调用start方法 ,start方法会自动调用run方法,在上述例子中run方法被我们重写。

方法二 :
创建Thread实例时,传入一个Runnable实例

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start(); // 启动新线程
    }
}
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}

如何更准确的体现多线程的特点:

public class Main {
    public static void main(String[] args) {
        System.out.println("main start...");
        Thread t = new Thread() {
            public void run() {
                System.out.println("thread run...");
                System.out.println("thread end.");
            }
        };
        t.start();
        System.out.println("main end...");
    }
}

在上述例子中,单线程操作,最终输出的结果:

main start...
thread run...
thread end.
main end...

而实际上多线程结果为:

main start...
main end...
thread run...
thread end.

在执行start方法时就已经自动创建了一线程用来执行run方法,而主线程仍然执行自己的方法输出main end...,因此会出现以上结果。当然以上结果并不确定。
线程可以被迫停止一段时间,方法为Thread.sleep(int),我们可以在某个线程内调用它。
注意sleep传入的参数为毫秒。

线程可以设定优先级

Thread.setPriority(int n) // 1~10, 默认值5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值