Java中有两种实现多线程的方法:Thread类,Runnable接口.下面的代码简单介绍了这两种方法.
Thread类:继承Thread类并重新实现其中的run()方法
public class MyThread extends Thread {
int count;
String name;
public MyThread(String name, int ct) {
this.name = name;
count = ct;
System.out.println("创建线程:" + name);
}
public void run() {
for (int i = 1; i < count + 1; i++) {
System.out.println("运行:" + name + "(" + i + ")");
}
}
public static void main(String args[]) {
new MyThread("Thread1", 5).start();
new MyThread("Thread2", 3).start();
new MyThread("Thread3", 4).start();
}
}
Runnable接口:Runnable中只定义了一个run()方法,实现Runnable的对象中必须定义此方法.在新建Thread对象时将实现Runnable的对象作为参数传入,Tread对象会调用其中的run()方法.
public class MyRunnable implements Runnable {
int count;
String name;
public MyRunnable(String name, int ct) {
this.name = name;
count = ct;
System.out.println("创建线程:" + name);
}
public void run() {
for (int i = 1; i < count + 1; i++) {
System.out.println("运行:" + name + "(" + i + ")");
}
}
public static void main(String args[]) {
new Thread(new MyRunnable("Thread1", 5)).start();
new Thread(new MyRunnable("Thread2", 3)).start();
new Thread(new MyRunnable("Thread3", 4)).start();
}
}
博客介绍了Java中实现多线程的两种方法。一是继承Thread类并重新实现run()方法;二是实现Runnable接口,在新建Thread对象时将实现Runnable的对象作为参数传入,由Thread对象调用run()方法,还给出了相应的代码示例。
1626

被折叠的 条评论
为什么被折叠?



