zoukankan      html  css  js  c++  java
  • java学习笔记-Thread

    java定义了创建线程的两种方法
    1.实现Runnable接口
    2.扩展Thread类本身

    1.实现Runnable接口:

    可以依托任何Runnable接口的对象来创建线程。但是为了实现Runnable接口,类需要实现run()方法。

    创建了实现Runnable接口的类之后,可以在类中实例化Thread类型的对象。Thread类定义了几个构造函数,下面实例中使用的构造函数如下:

    Thread(Runnable threadOb,String threadName) //该构造函数中,threadOb是实现了Runnable接口的类的实例或对象;

    实例:

    实现Runnable接口的类NewThread代码:

    public class NewThread implements Runnable{
    	Thread t;
    	public NewThread() {
    		//this是实现Runnable接口的类的实例
    		t=new Thread(this,"Demo Thread");
    		System.out.println("Child thread:"+t);
    		t.start();
    	}
    	
    	public void run() {
    		try {
    			for(int i=5;i>0;i--)
    				System.out.println("Child thread:"+i+":"+Thread.currentThread());
    			Thread.sleep(500);
    		} catch (InterruptedException e) {
    			System.out.println("Child Interrupted.");
    		}
    		System.out.println("Exiting Child thread.");
    	}	
    }

    测试类ThreadDemo代码:

    public class ThreadDemo {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		new NewThread();
    		try{
    			for(int i=5;i>0;i--){
    				System.out.println("Main Thread:"+i+":"+Thread.currentThread());
    				Thread.sleep(1000);
    			}
    		}catch (InterruptedException e) {
    			System.out.println("Main thread Interrupted.");
    		}
    		System.out.println("Exiting Main thread.");
    	}	
    }

    运行结果如下图:

    ps:Thread.currentThread()方法输出的是当前线程线程名称,优先级5,线程所处的线程组main。

    未完待续...

  • 相关阅读:
    团队项目 NABCD介绍
    java web项目通过外网ip访问
    第七周总结
    全球疫情可视化展示
    第六周总结
    软工小队——团队介绍
    Android端疫情数据统计与现实——Android连接Mysql
    android SDK SDK Manager.exe 无法打开,一闪而过最终解决办法 (转)
    第五周总结
    Java代码编写规范(转)
  • 原文地址:https://www.cnblogs.com/pangblog/p/3304135.html
Copyright © 2011-2022 走看看