1.java單線程的實現 一個任務一個人獨立完成
public class SingletonThread { @SuppressWarnings("static-access") public static void main(String[] args) { Thread t =Thread.currentThread(); t.setName("單例線程");
//有1000條數據需要更新,由一個人來完成 for(int i=0;i<1000;i++){
try {
System.out.println(t.getName()+"正在執行"+i); //t.sleep(500); //線程休眠中 } catch (InterruptedException e) { System.out.println("線程出現錯誤了!!"); } } } }
2.java多線程的實現 一個任務多個人來同時進行並完成
①繼承Thread類,並重寫run方法
public class ThreadImpl { public static void main(String[] args) {
//這里也有1000條數據數據需要更新,就分3個人來進行完成 Thread t1=new ThreadTest("t1", 300); Thread t2=new ThreadTest("t2", 300); Thread t3=new ThreadTest("t3", 400); t1.start(); t2.start(); t3.start(); } } class ThreadTest extends Thread{ private String name; private int ts; public ThreadTest(String name, int ts) { this.name = name; this.ts= ts; } public void run() { try { //sleep(ms);
for(int i=0;i<=ts;i++){
System.out.println(name+"正在執行"+i);
} } catch (InterruptedException e) { System.out.println("線程運行中斷異常"); } System.out.println("名字叫"+name+"的線程開始休眠"+ms+"毫秒"); } }
②實現runnable接口,重寫run方法
public class RunnableImpl { public static void main(String[] args) { RunnableTest r1=new RunnableTest(); Thread t=new Thread(r1); t.start(); } } class RunnableTest implements Runnable{ @Override public void run() { // TODO Auto-generated method stub } }
這是一個線程模擬的售票系統:
class MyThread implements Runnable{ private int ticket=10; //10張車票 public void run(){ for(int i=0;i<=20;i++){ if(this.ticket>0){ System.out.println(Thread.currentThread().getName()+"正在賣票:"+this.ticket--); } } } } public class ThreadTicket{
public static void main(String[] args) { //資源共享 MyThread mt=new MyThread(); new Thread(mt, "1號窗口").start(); new Thread(mt, "2號窗口").start(); new Thread(mt, "3號窗口").start(); } }
【運行結果】:
1號窗口正在賣票:9
1號窗口正在賣票:7
2號窗口正在賣票:6
3號窗口正在賣票:5
2號窗口正在賣票:4
1號窗口正在賣票:3
1號窗口正在賣票:2
1號窗口正在賣票:1
3號窗口正在賣票:8
2號窗口正在賣票:10