1.什么是线程
2.创建多线程 (方式一)
1 /* 2 创建多线程 3 方式一: 继承Thread类 4 1.子类继承Thread 5 2.重写run() --》 此线程执行的具体代码 6 3.在主线程中创建子类对象 7 4.通过此对象调用 start() 8 9 */ 10 11 //测试 : 输出100以内的偶数 12 //子线程 13 class MyThread extends Thread { 14 @Override 15 public void run() { 16 for (int i = 0; i < 100; i++) { 17 if (i % 2 ==0){ 18 System.out.println(i); 19 } 20 } 21 22 } 23 } 24 25 26 //主线程 27 public class ThreadTest{ 28 public static void main(String[] args) { 29 MyThread myThread = new MyThread(); 30 //start() : 1.启动线程 2.执行run()方法 31 //如果直接调用子线程的run()方法 , 就不是多线程了 32 myThread.start(); 33 34 for (int i = 0; i < 100; i++) { 35 if (i % 2 !=0){ 36 System.out.println(i+"***************main()********************"); 37 } 38 } 39 } 40 }
3.常用的Thread方法
4.多线程实践
/* 多线程案例:三个窗口卖票 */ class Window extends Thread{ //总票数 //注意 : 三个线程共用一个变量 , 必须声明为 static private static int ticket=100; @Override public void run() { while(true){ if (ticket > 0){ System.out.println(Thread.currentThread().getName()+"买票, 票号为 :"+ticket); ticket--; }else{ break; } } } } public class SellTicket { public static void main(String[] args) { Window window1 = new Window(); Window window2 = new Window(); Window window3 = new Window(); window1.setName("1"); window2.setName("2"); window3.setName("3"); window1.start(); window2.start(); window3.start(); } }
5.线程的优先级
未完待续!