/* * 常见的创建线程的方法有两种: * 1.扩展java.lang.Thread类 * 2.事项java.lang.Runnable接口 * * 第一种方法需要覆盖run方法,并在run方法中写入想在这个线程中想要执行的代码,一个线程创建之后需要使用start方法启动这个线程 * 当run()方法返回或者抛出异常的时候,线程会死掉并且被垃圾收集。 * 每一个线程都有自己的一个名字,这是常用的方法。而且每个线程都有自己的状态,new,runnable,blocked,waiting, * time_waiting,terminated * 线程的状态封装在java.lang.Thread.State这个枚举类型中。 * */ public class ThreadDemo extends Thread { public void run() { for(int i=0;i<=10;i++) { System.out.println(i); } try{ sleep(1000); }catch(InterruptedException e){} } public static void main(String[] args) { new ThreadDemo().start(); } }
因为我们不能总是从主类来扩展Thread类,因为java不是指出多继承的,这样就需要我们重新写一个类继承Thread,这样在主函数中直接调用就可以了。
类似的,我们可以使用Runnable类接口来实现一个线程。
class MyThread extends Thread { public void run() { for(int i=0;i<=10;i++) { System.out.println(i); try{ sleep(1000); }catch(InterruptedException e){} } } } public class ThreadDemo { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } }
class MyThread implements Runnable { public void run() { for(int i=0;i<10;i++) { System.out.println(i); try{ Thread.sleep(1000); } catch(InterruptedException e){} } //这里需用调用一个静态方法,方法返回当前正在执行的线程,然后调用这个线程的sleep()方法。 } } public class ThreadDemo { public static void main(String[] args) { MyThread myThread = new MyThread(); Thread thread = new Thread(myThread); thread.start(); } }
//使用了一个多线程
import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; public class ThreadDemo extends JFrame { JLabel countUpLabel = new JLabel("Count Up"); JLabel countDownLabel = new JLabel("Count Down"); class CountUpThread extends Thread { public void run() { int count = 1000; while(true) { try{ sleep(1000);} catch(InterruptedException e){} if(count==0) count=1000; countUpLabel.setText(Integer.toString(count--)); } } } class CountDownThread extends Thread { public void run() { int count=0; while(true) { try{ sleep(50); }catch(InterruptedException e){} if(count==1000) count = 0; countDownLabel.setText(Integer.toString(count++)); } } } public ThreadDemo(String title) { super(title); init(); } private void init() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.getContentPane().setLayout(new FlowLayout()); this.add(countUpLabel); this.add(countDownLabel); this.pack(); this.setVisible(true); new CountUpThread().start(); new CountDownThread().start(); } private static void constructGUI() { JFrame.setDefaultLookAndFeelDecorated(true); ThreadDemo frame = new ThreadDemo("ThreadDemo"); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable(){ public void run() { constructGUI(); } }); } }