课堂代码

    1. package kt;
    2. //继承Thread类
    3. public class L1 extends Thread{
    4. int count = 0;
    5. public L1(String name){
    6. super(name);
    7. }
    8. public void run(){
    9. for(int i = 0;i < 5;i++){
    10. count++;
    11. System.out.println(count + ":" + this.getName());
    12. }
    13. }
    14. public static void main(String[] args){
    15. L1 p = new L1("线程1");
    16. int count = 0;
    17. p.start();
    18. for(int i = 0;i < 5 ; i++){
    19. count ++;
    20. System.out.println(count + ":main");
    21. }
    22. }
    23. }
    1. package kt;
    2. //继承类
    3. public class L2 extends Thread{
    4. int count = 0;
    5. static int c = 0;
    6. public L2(String name){
    7. super(name);
    8. }
    9. public void run(){
    10. for(int i = 0;i < 5;i++){
    11. c++;
    12. System.out.println(
    13. c + ":"
    14. + Thread.currentThread() + ":"
    15. + this.getName());
    16. }
    17. }
    18. public static void main(String[] args){
    19. L2 p1 = new L2("线程1");
    20. L2 p2 = new L2("线程2");
    21. p1.start();
    22. p2.start();
    23. }
    24. }
    1. package kt;
    2. //接口类
    3. public class L3 implements Runnable{
    4. int count = 1;
    5. int number;
    6. public L3(int i){
    7. number = i;
    8. System.out.println("创建线程"+number);
    9. }
    10. public void run(){
    11. while(true){
    12. System.out.println("线程"+number+"计数"+count);
    13. if(++count == 3){
    14. return;
    15. }
    16. }
    17. }
    18. public static void main(String args[]){
    19. for(int i = 0;i<3;i++){
    20. Thread p = new Thread(new L3(i+1));
    21. p.start();
    22. }
    23. }
    24. }
    1. package kt;
    2. /*
    3. * Runnable接口类
    4. * */
    5. public class L4 implements Runnable{
    6. int n;
    7. public void run(){
    8. for(int i = 1;i < n;i++){
    9. System.out.println(i + " ");
    10. }
    11. }
    12. public static void main(String args[]){
    13. L4 my = new L4();
    14. my.n = 10;
    15. Thread p1 = new Thread(my);
    16. p1.start();
    17. }
    18. }