- public class Demo {
-
- public static void main(String[] args){
- ThreadDemo t1=new ThreadDemo();
- ThreadDemo t2=new ThreadDemo();
- t1.start();
- t2.start();
- int i = 0;
- while(true){
-
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- System.out.println("Thread-main="+ i++);
- }
- }
- }
- class ThreadDemo extends Thread{
- int i = 0;
- public void run(){
- while(true){
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"="+i++);
- }
- }
- }
复制代码 是交互的,建议把循环次数弄大点,或者让线程睡会,就有明显效果了.
次数太小,都是双核cpu且性能不错,所以会导致一个线程执行完了,下一个才抢到cpu执行权. |