1、通过继承Thread编写多线程类
1 package org.zln.thread; 2 3 import java.util.Date; 4 5 /** 6 * Created by coolkid on 2015/6/21 0021. 7 */ 8 public class TestThread extends Thread{ 9 private int time;//休眠时间 10 private String user;//调用用户 11 12 public TestThread(int time, String user) { 13 this.time = time; 14 this.user = user; 15 } 16 17 @Override 18 public void run() { 19 while (true){ 20 try { 21 System.out.println(Thread.currentThread().getName()+"\t"+user+" 休息 "+time+"ms-"+new Date()); 22 Thread.sleep(time); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 } 27 } 28 29 public static void main(String[] args) { 30 Thread thread1 = new TestThread(1000,"Jack"); 31 Thread thread2 = new TestThread(3000,"Mike"); 32 thread1.start(); 33 thread2.start(); 34 } 35 }
设置线程优先级:thread2.setPriority(Thread.MAX_PRIORITY);
这样就能够保证每次都是thread2先于thread1执行
2、通过实现Runnable接口编写多线程类
1 package org.zln.thread; 2 3 import java.util.Date; 4 5 /** 6 * Created by coolkid on 2015/6/21 0021. 7 */ 8 public class TestRunnable implements Runnable { 9 private int time;//休眠时间 10 private String user;//调用用户 11 12 public TestRunnable(int time, String user) { 13 this.time = time; 14 this.user = user; 15 } 16 17 @Override 18 public void run() { 19 while (true){ 20 try { 21 System.out.println(Thread.currentThread().getName()+"\t"+user+" 休息 "+time+"ms-"+new Date()); 22 Thread.sleep(time); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 } 27 } 28 29 public static void main(String[] args) { 30 Thread t1 = new Thread(new TestRunnable(1000,"Jack")); 31 Thread t2 = new Thread(new TestRunnable(3000,"Mike")); 32 t2.setPriority(Thread.MAX_PRIORITY); 33 t1.start(); 34 t2.start(); 35 } 36 }