Two different ways:
1 . Inherit Thread 2. Implement Runnable
1.
classMyThreadextendsthread{ Public Static intnum = 0; @Override Public voidrun () {//TODO auto-generated Method Stub while(num<100) {System.out.println (Thread.CurrentThread (). GetName ()+ "+" + num++); } }} Public classTest { Public Static voidMain (string[] args) {MyThread thread01=NewMyThread (); MyThread thread02=NewMyThread (); Thread01.start (); Thread02.start (); }}
2.
classYourthreadImplementsRunnable {Private Static intnum = 0; @Override Public voidrun () {//TODO auto-generated Method Stub while(Num < 100) {System.out.println (Thread.CurrentThread (). GetName ()+ "+" + num++); } }} Public classTest { Public Static voidMain (string[] args) {Thread thread01=NewThread (NewYourthread (), "t01"); Thread thread02=NewThread (NewYourthread (), "t02"); Thread01.start (); Thread02.start (); }}
This synchronization problem does not occur every time.
2016-7-5 Java:thread