• Java 线程:(一)


    .线程的创建和启动

    package com.gatsby.test;
    
    class MyThread extends Thread {
    
    	// 覆写run()方法,作为线程 的操作主体 
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		super.run();
    
    		for (int i = 1; i < 13; i++) {
    			System.out.println( " ThreagetId->" + getId() + "  " + i);
    		}
    
    	}
    
    }
    
    public class RunnableDemo01 {
    	public static void main(String[] args) {
    
    		new MyThread().start();
    
    		 // 实例化对象 
    		MyThread myThread2 = new MyThread();
    		//调用线程主体
    		myThread2.start();
    
    	}
    }
    

     程序运行:

     ThreagetId->11  1
     ThreagetId->10  1
     ThreagetId->10  2
     ThreagetId->10  3
     ThreagetId->10  4
     ThreagetId->11  2
     ThreagetId->10  5
     ThreagetId->10  6
     ThreagetId->10  7
     ThreagetId->10  8
     ThreagetId->11  3
     ThreagetId->10  9
     ThreagetId->10  10
     ThreagetId->10  11
     ThreagetId->10  12
    

      

    package com.gatsby.test;
    
    //通过实现Runnable接口来创建线程类
    class MyRunnable implements Runnable{
    
    	// run方法同样是线程执行体
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		for (int i = 1; i < 13; i++) {
    			System.out.println( " ThreagetId->" +Thread.currentThread().getId() + "  " + i);
    		}
    		
    	}
    	
    }public class RunnableDemo02 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		MyRunnable myRunnable = new MyRunnable();
    		new Thread(myRunnable).start();
    	}
    
    }
    

      

  • 相关阅读:
    20210312
    20210311
    20210310
    例5-1
    例5-2
    例4-12-2
    例4-12
    例4-11
    例4-10
    例4-9
  • 原文地址:https://www.cnblogs.com/crushgirl/p/13516189.html
Copyright © 2020-2023  润新知