创建java线程的代码
时间: 2023-03-14 14:51:22 浏览: 74
要创建一个Java线程,可以使用Thread类的两种构造函数:Thread(Runnable target),Thread(Runnable target,String name)。第一种构造函数用于创建一个不带名字的线程,第二种构造函数用于创建一个带名字的线程。 例如:Thread thread = new Thread(new Runnable(){ public void run(){ // run code here } }); 或者 Thread thread = new Thread(new Runnable(){ public void run(){ // run code here } }, "My Thread");
相关问题
java线程创建的代码
Java线程可以通过两种方式创建:
1. 继承Thread类,重写run()方法
```
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
```
2. 实现Runnable接口,实现run()方法
```
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
```
然后,通过创建Thread对象并传入MyThread或MyRunnable对象来创建线程:
```
Thread myThread = new MyThread();
myThread.start();
Runnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
```
java线程的创建方式代码
在Java中,创建线程有两种方式:继承Thread类和实现Runnable接口。以下是两种方式的示例代码:
1. 继承Thread类:
```java
class MyThread extends Thread {
public void run() {
// 线程要执行的代码
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
```
2. 实现Runnable接口:
```java
class MyRunnable implements Runnable {
public void run() {
// 线程要执行的代码
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // 启动线程
}
}
```
无论使用哪种方式,都需要在`run()`方法中定义线程要执行的代码,然后通过调用`start()`方法启动线程。注意,调用`run()`方法只会在当前线程中执行,而调用`start()`方法会创建一个新的线程并在新线程中执行`run()`方法中的代码。