Java中的多线程

public class Main {
    public static void main(String[] args) {
	// 通过创建thread对象来创建新的线程
	Thread thread = new Thread() {
	    public void run() {
		while (true) {
		    try {
			Thread.sleep(500);
		    } catch (InterruptedException ex) {
			ex.printStackTrace();
		    }
		    System.out.println(this.getName());
		}
	    }

	};
	thread.start();
	// 创建一个带有Runnable的对象作为参数的Thread的线程
	Thread thread2 = new Thread(new Runnable() {
	    @Override
	    public void run() {
		while (true) {
		    try {
			Thread.sleep(1500);
		    } catch (InterruptedException ex) {
			ex.printStackTrace();
		    }
		    System.out.println(Thread.currentThread().getName());
		}

	    }
	});
	thread2.start();
	//下面的运行结果,只会输出run1中的代码
	new Thread(
		//runnable是作为父类的参数传进去 的
		new Runnable() {
		    //run1
	    public void run() {
		while (true) {
		    try {
			Thread.sleep(1500);
		    } catch (InterruptedException ex) {
			ex.printStackTrace();
		    }
		    System.out.println("Runnable"+Thread.currentThread().getName());
		}
	    }
	}) {
	    //run2
	    public void run() {
		while (true) {
		    try {
			Thread.sleep(1500);
		    } catch (InterruptedException ex) {
			ex.printStackTrace();
		    }
		    System.out.println("Thread"+Thread.currentThread().getName());
		}
	    }
	}.start();
    }
}

你可能感兴趣的:(Java中的多线程)