怎样简单的实现多线程(Thread类和Runnable接口)

第一种:继承Thread类

步骤:

    1、创建一个 ThreadTest 类,去继承 Thread 类

    2、重写 Thread 类的 run() 方法,在 run() 方法里面做点可以看出线程的运行,比如打印一下

    3、写一个测试类,创建一个 Thread 的一个实例

代码:

public class Test {

	public static void main(String[] args) {

		// 创建类对象
		TestThread test = new TestThread();

		// 创建两个线程对象,该方法可以有多个参数,此处的参数为目标对象和线程名
		Thread thread = new Thread(test, "A");
		Thread thread2 = new Thread(test, "B");

		// 开始线程(start()只是让当前的状态转换成就绪状态,还需要调度CPU才能启动run()方法运行)
		thread.start();
		thread2.start();
	}
}

class TestThread extends Thread {

	@Override
	public void run() {
		for (int i = 1; i < 5; i++) {

			// tip:Thread.currentThread().getName(),此方法是获取当前线程名
			System.out.println(Thread.currentThread().getName() + ":第" + i + "次运行");
			try {

				// 创建两个线程,每运行一次就会休眠1000ms(1s),这样才能让其他线程有运行的空间
				// 且该方法可能会有异常,要try catch一下,Thread.sleep(1000)尚可
				sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

第二种:实现Runnable接口

tips:因为上个是继承了Thread类,所以上面调用Sleep方法的时候,可以不加Thread。
可能因为JDK版本的问题,可能运行结果出来的时候会出现一些看起来不符合人意的东西,可以和我联系。当真的是更新的太快,都学不动了!
public class RunnableTest{
	public static void main(String[] args) {
		
		Test test = new Test();
		Thread thread = new Thread(test,"A");
		
		thread.start();
	}
}

class Test implements Runnable{

	@Override
	public synchronized void run() {
		for (int i = 1; i < 5; i++) {
			System.out.println(Thread.currentThread().getName() + ":第" + i + "次运行");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39216644/article/details/80684722