欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 传统多线程

程序员文章站 2022-05-28 18:24:09
...

/**
 * 传统多线程
 */
public class TraditionalThread {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread thread=new Thread(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("1:"+Thread.currentThread().getName());
					System.out.println("2:"+this.getName());
				}
			}
			
		};
		thread.start();
		
		
		Thread thread2=new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1:"+Thread.currentThread().getName());
					//System.out.println("2:"+this.getName());
				}
			}
		});
		thread2.start();
		
		//创建了一个 Thread 的子类重写了run方法,并且 给构造函数传递了  runnable接口的实例 ,结果呢只会运行 Thread子类的run方法不会运行Runnable接口
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("runnable:"+Thread.currentThread().getName());
					//System.out.println("2:"+this.getName());
				}
			}
		}){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread:"+Thread.currentThread().getName());
					//System.out.println("2:"+this.getName());
				}
			}
		}.start();
		
		//创建了一个 Thread 的子类没有重写了run方法,并且 给构造函数传递了  runnable接口的实例 ,结果呢会运行 TRunnable接口中run方法中代码
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("runnableAS:"+Thread.currentThread().getName());
					//System.out.println("2:"+this.getName());
				}
			}
		}){}.start();
		
		
	}

}
相关标签: 多线程