首页 > 代码库 > JAVA单线程以及java多线程的实现方式

JAVA单线程以及java多线程的实现方式

1.java单线程的实现

public class SingletonThread {
    @SuppressWarnings("static-access")
	public static void main(String[] args) {
		 Thread t =Thread.currentThread();
		 t.setName("单例线程");
		 System.out.println(t.getName()+" 正在运行");
		 for(int i=0;i<2000;i++){
			 System.out.println("线程正在休眠:"+i);
			 try {
				t.sleep(500);
			} catch (InterruptedException e) {
			    System.out.println("线程出现错误了!!");
			}
		 }
    	
	}
}


2.java多线程的实现

①继承Thread类,并重写run方法

public class ThreadImpl {
    public static void main(String[] args) {
		Thread t1=new ThreadTest("t1", 200);
		Thread t2=new ThreadTest("t2", 100);
		Thread t3=new ThreadTest("t3", 300);
		t1.start();
		t2.start();
		t3.start();
	}
}

class ThreadTest extends Thread{
	private String name;
	private int ms;
	public ThreadTest(String name, int ms) {
		
		this.name = name;
		this.ms = ms;
	}
	
	public void run() {
		try {
			sleep(ms);
		} catch (InterruptedException e) {
		System.out.println("线程运行中断异常");
		}
		
		System.out.println("名字叫"+name+"的线程开始休眠"+ms+"毫秒");
	}
	
}
结果:

名字叫t2的线程开始休眠100毫秒
名字叫t1的线程开始休眠200毫秒
名字叫t3的线程开始休眠300毫秒

②实现runnable接口,重写run方法

public class RunnableImpl {
	public static void main(String[] args) {
		RunnableTest r1=new RunnableTest();
	    Thread t=new Thread(r1);
	     t.start();
	}
    
}

class RunnableTest implements Runnable{
    
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}
	
}




JAVA单线程以及java多线程的实现方式