在java中开启线程有4种方式,分别是
(1)继承Thread类创建线程
(2)实现Runnable接口创建线程
(3)使用Callable和Future创建线程
(4)使用线程池例如用Executor框架
作为新手,我最近着重复习了前两种方法,通过实际操作可以感受到其不同之处。
Runnable
设置类X实现了runnable接口,重写其中的run方法(加上sychronized关键字),并在main函数中创建X的实例对象that,用that开启2个线程。
package JavaTutorial;
import static java.lang.Thread.sleep;
public class SychronizedLock {
public static void main(String[] args) {
X that = new X();
(new Thread(that)).start();
(new Thread(that)).start();
}
}
class X implements Runnable{
private int x;
private int y;
@Override
public synchronized void run() {
for (;;){
x++;
y++;
System.out.println("x="+x+",y="+y);
try {
sleep(5