创建Threadtest类:
1 package org.hanqi.thread; 2 3 //支持多线程 4 //1.继承Thread 5 //2.覆盖run方法 6 public class TestThread extends Thread { //extends 7 8 //重写 9 public void run() 10 { 11 for(int i=0;i<10;i++) 12 { 13 System.out.print(i+" "); 14 try { 15 //线程的休眠方法(毫秒) 16 Thread.sleep(1000); 17 } catch (InterruptedException e) { 18 // TODO 自动生成的 catch 块 19 e.printStackTrace(); 20 } 21 } 22 } 23 }
创建TestThread1类:
1 package org.hanqi.thread; 2 3 public class TestThread1 implements Runnable{ //implements 4 5 @Override 6 public void run() { 7 for(int i=0;i<10;i++) 8 { 9 System.out.println(i); 10 try { 11 //线程的休眠方法(毫秒) 12 Thread.sleep(1000); 13 } catch (InterruptedException e) { 14 // TODO 自动生成的 catch 块 15 e.printStackTrace(); 16 } 17 } 18 } 19 }
创建Test1类运行:
1 package org.hanqi.thread; 2 3 public class Test1 { 4 5 public static void main(String[] args) { 6 7 for(int i=0;i<10;i++) 8 { 9 System.out.print(i+" "); 10 try { 11 //线程的休眠方法(毫秒) 12 Thread.sleep(1000); 13 } catch (InterruptedException e) { 14 // TODO 自动生成的 catch 块 15 e.printStackTrace(); 16 } 17 } 18 System.out.println(); 19 TestThread tt = new TestThread(); 20 //启动多线程 21 tt.start(); 22 TestThread tt1 = new TestThread(); 23 //启动多线程 24 tt1.start(); 25 //启动实现接口方式的多线程 26 Thread tt2 = new Thread(new TestThread1()); 27 tt2.start(); 28 } 29 }
运行结果为:
创建Test2类:
1 package org.hanqi.thread; 2 3 public class Test2 { 4 5 public static void main(String[] args) { 6 7 //匿名实现接口方式 8 //出生 9 Thread t = new Thread(new Runnable(){ 10 11 @Override 12 public void run() { 13 14 //运行 15 for(int i=0;i<10;i++) 16 { 17 System.out.println(i); 18 try { 19 //休眠 20 Thread.sleep(100); 21 } catch (InterruptedException e) { 22 // TODO 自动生成的 catch 块 23 e.printStackTrace(); 24 } 25 } 26 27 }}); 28 t.start();//就绪 运行 29 try { 30 //t.sleep(1000);//休眠 31 t.wait();//等待 32 33 t.notify();//通知(唤醒) 34 t.notifyAll(); 35 t.interrupt(); 36 37 //t.wait(1000); 38 } catch (InterruptedException e) { 39 // TODO 自动生成的 catch 块 40 e.printStackTrace(); 41 } 42 } 43 }
解决多线程重复卖票方法(关键字synchronized):
package org.hanqi.thread; public class MaiPiao implements Runnable{ //当前票数 private int count = 10; @Override public void run() { //买票 while(true) { //线程同步块 synchronized ("同步标记:0;1") { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if(count>0) { count--;//卖出一张 System.out.println(Thread.currentThread().getName()+"剩余票的数量="+count+"张"); } // 当前线程 的 名字 else { break; } } } } public static void main(String[] args) { MaiPiao m = new MaiPiao(); Thread t1 = new Thread(m, "售票点1"); Thread t2 = new Thread(m, "售票点2"); Thread t3 = new Thread(m, "售票点3"); t1.start(); t2.start(); t3.start(); } }
运行结果为:
,且结果随机
附相关思维导图: