Java基础之多线程的基本实现

1、实现方式一:继承Thread类,重写run方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Demo{
	public static void main(String [] args){
		SAThread thread1 = new SAThread();
		SAThread thread2 = new SAThread();
		thread1.start();
		thread2.start();
	}
 
}
class SAThread extends Thread{
	public void run(){
		System.out.println("SAThread-->"+Thread.currentThread());
	}
}

运行结果:
SAThread–>Thread[Thread-1,5,main]
SAThread–>Thread[Thread-0,5,main]

2、实现Runnable接口,创建Thread对象时将该接口实例传进去即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo{
	public static void main(String [] args){
		SARunnable runnable = new SARunnable();
		Thread thread1 = new Thread(runnable);
		Thread thread2 = new Thread(runnable);
		thread1.start();
		thread2.start();
	}
 
}
class SARunnable implements Runnable{
	public void run(){
		System.out.println("SAThread-->"+Thread.currentThread());
	}
}

运行结果:
SAThread–>Thread[Thread-1,5,main]
SAThread–>Thread[Thread-0,5,main]

One thought on “Java基础之多线程的基本实现

  1. Pingback: Java基础之synchronized同步的使用 | 小龙虾博客 (Crayfish)

Leave a Reply