两种方式:
1.继承Thread 2.实现Runnable
1.
class MyThread extends Thread{ public static int num = 0; @Override public void run() { // TODO Auto-generated method stub while(num<100) { System.out.println(Thread.currentThread().getName() + " -> "+ num++); } } } public class Test { public static void main(String[] args) { MyThread thread01 = new MyThread(); MyThread thread02 = new MyThread(); thread01.start(); thread02.start(); } }
2.
class YourThread implements Runnable { private static int num = 0; @Override public void run() { // TODO Auto-generated method stub while (num < 100) { System.out.println(Thread.currentThread().getName() + " -> " + num++); } } } public class Test { public static void main(String[] args) { Thread thread01 = new Thread(new YourThread(),"t01"); Thread thread02 = new Thread(new YourThread(),"t02"); thread01.start(); thread02.start(); } }
这种同步问题不会每次都出现.