使用Thread类实现多线程
使用Runnable接口实现多线程
public class ThreadExtendsExample {
/**
* @param args
*/
public static void main(String[] args) {
LeftThread1 left = new LeftThread1();
RightThread1 right = new RightThread1();
left.start();
right.start();
for (int i = 0; i < 5; i++) {
System.out.println("I am the MainThread " + i);
}
}
}
class LeftThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am the LeftThread " + i);
}
}
}
class RightThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am the RightThread " + i);
}
}
}
使用Runnable接口实现多线程
public class ThreadRunnbaleExample {
/**
* @param args
*/
public static void main(String[] args) {
LeftThread2 lt = new LeftThread2();
RightThread2 rt = new RightThread2();
lt.getLthread2().start();
rt.getRthread2().start();
for(int i=0;i<5;i++){
System.out.println("I am the MainThread "+i);
}
}
}
class LeftThread2 implements Runnable {
private Thread lthread2 = null;
LeftThread2() {
lthread2 = new Thread(this);
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am the LeftThread " + i);
}
}
public Thread getLthread2() {
return lthread2;
}
}
class RightThread2 implements Runnable {
private Thread rthread2 = null;
RightThread2() {
rthread2 = new Thread(this);
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am the RightThread " + i);
}
}
public Thread getRthread2() {
return rthread2;
}
}