java创建线程的所有代码
时间: 2023-02-21 07:34:30 浏览: 68
Java 创建线程有两种方法:通过实现 Runnable 接口和通过继承 Thread 类。
方法一:实现 Runnable 接口
```
class MyRunnable implements Runnable {
public void run() {
// 线程代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
```
方法二:继承 Thread 类
```
class MyThread extends Thread {
public void run() {
// 线程代码
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
```
请注意,在线程中的代码不能直接调用,必须通过调用 start() 方法来启动线程。
相关问题
Java创建线程代码
在Java中,创建线程主要有两种方式:继承Thread类和实现Runnable接口。这里我会分别介绍这两种方法。
1. 继承Thread类:
```java
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
System.out.println("Thread is running");
}
public static void main(String[] args) {
// 创建线程实例,并调用start()方法启动线程
MyThread thread = new MyThread();
thread.start();
}
}
```
在这个例子中,`MyThread` 类继承自 `Thread` 类,重写 `run()` 方法为线程主体。在 `main()` 方法中,创建 `MyThread` 的实例并调用 `start()` 启动线程。
2. 实现Runnable接口:
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("Thread is running");
}
public static void main(String[] args) {
// 创建Runnable实例,然后创建Thread并传入Runnable实例
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
```
这里,`MyRunnable` 类实现了 `Runnable` 接口,同样重写 `run()` 方法。在 `main()` 中,创建 `Runnable` 的实例,然后传递给 `Thread` 构造函数创建线程并启动。
Java 创建多线程代码
以下是 Java 中创建多线程的代码示例:
1. 继承 Thread 类:
```java
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
```
2. 实现 Runnable 接口:
```java
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable();
MyRunnable r2 = new MyRunnable();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
```
3. 使用匿名内部类:
```java
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
// 线程执行的代码
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
// 线程执行的代码
}
});
t1.start();
t2.start();
}
}
```