写一个多线程的java代码
时间: 2023-04-02 22:04:08 浏览: 73
好的,我可以回答这个问题。以下是一个简单的多线程 Java 代码示例:
```
public class MyThread implements Runnable {
private String threadName;
MyThread(String name) {
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
System.out.println("Running " + threadName);
try {
for(int i = 4; i > ; i--) {
System.out.println("Thread: " + threadName + ", " + i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public static void main(String args[]) {
System.out.println("Main thread starting.");
MyThread mt1 = new MyThread("Thread-1");
MyThread mt2 = new MyThread("Thread-2");
Thread t1 = new Thread(mt1);
Thread t2 = new Thread(mt2);
t1.start();
t2.start();
System.out.println("Main thread ending.");
}
}
```
这个代码创建了两个线程,每个线程都打印出一些信息。在主线程中,我们创建了两个 MyThread 对象,并将它们分别传递给两个 Thread 对象。然后我们启动这两个线程,最后打印出一条信息表示主线程结束了。