java新开一个线程run_创建和启动一个Java线程

创建和启动一个Java线程

创建和启动线程

新建一个线程

Thread thread = new Thread();

启动一个 Java 线程,只需要调用它的 start() 方法

thread.start()

这个例子里没有写其他的代码,当线程启动之后马上就停止了。

有两个办法指定线程去执行代码。一种是创建一个 Thread 的子类,覆盖 run() 方法。第二种是传入一个实现 Runnable 接口的对象给 Thread 的构造方法。

线程子类

创建线程的子类

public class MyThread extends Thread {

public void run() {

System.out.println("MyThread running");

}

}

创建和启动线程

MyThread myThread = new MyThread();

myThread.start();

当然,匿名子类也是可以的

Thread thread = new Thread() {

public void run() {

System.out.println("MyThread Running");

}

};

thread.start();

实现 Runnable 接口

实现接口

public class MyRunnable implements Runnable {

public void run() {

System.out.println("MyRunnable running");

}

}

启动线程

Thread thread = new Thread(new MyRunnable());

thread.start();

也可使用实现 Runnable 接口的匿名类

Runnable myRunnable = new Runnable() {

public void run() {

System.out.println("Runnable running");

}

};

Thread thread = new Thread(myRunnable);

thread.start();

用子类还是实现接口?

都可以。不过我喜欢用实现接口的方式。

run() 和 start() 的区别

调用 start() 方法才是启动线程的正确姿势。

线程名称

给线程取个名字,可以和其它线程区分开来

Thread thread = new Thread("New Thread") {

public void run() {

System.out.println("run by: " + getName());

}

};

thread.start();

System.out.println(thread.getName());

MyRunnable runnable = new MyRunnable();

Thread thread = new Thread(runnable, "New Thread");

thread.start();

System.out.println(thread.getName());

Thread.currentThread()

Thread.currentThread() 方法返回一个执行 currentThread() 方法的 Thread 实例的引用。

Thread thread = Thread.currentThread();

一获取到 Thread 对象的引用,就可调用它的方法,比如获取它的名称

String threadName = Thread.currentThread().getName();

Java Thread Example

public class ThreadExample {

public static void main(String[] args) {

System.out.println(Thread.currentThread().getName());

for (int i = 0; i < 10; i++) {

new Thread("" + i) {

public void run() {

System.out.println("Thread: " + getName() + " running");

}

}.start();

}

}

}

打印结果

main

Thread: 0 running

Thread: 2 running

Thread: 3 running

Thread: 1 running

Thread: 4 running

Thread: 5 running

Thread: 6 running

Thread: 8 running

Thread: 9 running

Thread: 7 running

从打印结果可以看到,即使线程是按顺序(1,2,3...)执行 start() 方法的,thread 1 不一定是第一个打印消息的线程。因此线程是并发执行而不是顺序执行的。由 JVM 或者操作系统决定线程的执行顺序,和线程的 start() 方法执行顺序无关。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值