在java中使用Thread类代表线程,所有的线程对象都必须是Thread类或其子类的实例,创建线程有三种方式:
1.通过继承Thread类创建线程;
2.通过实现Runnable接口创建线程;
3.通过使用Callable和Future创建线程。
创建线程demo
1.继承Thread类创建线程:定义子类继承Thread类 -> 重写该子类的run()方法,run()方法的方法体即线程需要执行的任务 -> 创建Thread子类的实例(创建线程对象) -> 调用线程start()方法,启动线程。
如:创建两个线程,分别输出1~10.
public class ThreadTest {
public static void main(String[] args){
Thread t1 = new MyThread();
Thread t2 = new MyThread();
t1.start();
t2.start();
}
}
class MyThread extends Thread{
public void run(){
for(int i = 1; i <= 10; i++){
System.out.println(i);
System.out.println(Thread.currentThread());
}
}
}
2.实现Runnable接口创建线程:定义Runnable接口实现类 -> 重写该类的run()方法 -> 创建Runnable实现类的实例 -> 创建Thread对象(真正的线程对象) -> 调用线程start()方法,启动线程。这种方式将线程对象和线程任务对象分隔开,降低了耦合性,便于维护。
如:编写一个线程,实现窗口颜色变化。
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
MyRunnable r = new MyRunnable();
r.setSize(200, 200);
r.setVisible(true);
r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thread thread = new Thread(r);
thread.start();
}
}
class MyRunnable extends JFrame implements Runnable {
public void run(){
int i = 0;
JPanel panel = new JPanel();
panel.setSize(200, 200);
this.setContentPane(panel);
while (true){
i = i == 0 ? 1 : 0;
if(i == 0){
panel.setBackground(Color.BLACK);
}else {
panel.setBackground(Color.WHITE);
}
}
}
}
3.使用Callable和Future创建线程:定义Callable接口实现类 -> 重写call()方法 -> 创建该实现类实例 -> 使用Future Task类包装Callable对象 -> 创建Thread对象 -> 调用线程start()方法,启动线程 -> 调用FutureTask对象get()方法获得子线程执行结束后的返回值。
public class ThreadTest {
public static void main(String[] args){
MyCallableThread ct = new MyCallableThread();
FutureTask<Integer> ft = new FutureTask<Integer>(ct);
try {
//获取线程返回值
System.out.println("子线程的返回值:" + ft.get());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
class MyCallableThread implements Callable<Integer> {
public Integer call() throws Exception{
int i;
for(i = 1; i <= 10; i++){
System.out.println(i);
}
return i;
}
}