Thread theFirst = new Thread(myThread);
Thread theSecond = new Thread(myThread); 既然你在2个线程里使用了同一个myThread,那么当然有同步问题你为何不使用2哦 myThread和myThread2 呢? new 一个对象很复杂吗?

解决方案 »

  1.   

    利用同步方式实现。
    代码:class PrintCode implements Runnable{
       
        public static void main(String[]args){          PrintCode print = new PrintCode();    }}
      

  2.   

    按table键跳到提交了。。没写完继续同步方式:
    public class ThreadTest implements Runnable{

    public static void main(String[] args) throws Exception{
    // TODO Auto-generated method stub
    ThreadTest r1 = new ThreadTest();

    Thread t1 = new Thread(r1,"t1");
    Thread t2 = new Thread(r1,"t2");

    t1.start();
    t2.start();
    }

    public void run(){

    for(int i = 0; i < 50; i++){
    synchronized(this){

    try{

    if(Thread.currentThread().getName().equals("t1")){
    for(int j = 0; j < 10;j++){
    System.out.println("I'm the first.");
    }
    }else{
    for(int j = 0; j < 20;j++){
    System.out.println("I'm the second.");
    }
    }
    notify();
    wait();
    }catch(InterruptedException ex){


    }
    }
    }
    System.out.println("Done");
    System.exit(0);
    }

    }
      

  3.   

    以前对java线程感觉难以理解,后来用VxWorks做嵌入式,用到了它的互斥与同步信号量后感觉明朗了一些。建议可以看看VxWorks 信号量相关文献加深比较和理解。
      

  4.   

    Java 多线程编程之三:synchronized 关键字的使用
      

  5.   

    synchronized同步其实就是对共享资源访问时,那一个线程先到达,就先执行,等这个线程执行完了,再给其它的线程执行。
      

  6.   

    线程之间没有数据共用 就没有必要用同步synchronized
    lz的这个问题最好写两个类:class MyThread1 implements Runnable {
            public void run(){
                   System.out.println("this is first"); 
           }
        }
    }
    class MyThread2 implements Runnable {
            public void run(){
                   System.out.println("this is second"); 
           }
        }
    }  
      

  7.   

    我的思维大概是这样的,首先关于线程类的代码它有两个区别,一个是实现runnable接口,另一个是继承Thread类,重写run方法,在写继承类的时候需要注意这个类它是不是已经继承了其他父类,如果有的话,根据Java的类与多态性就不能再继承Thread类了,而是实现runnable方法,这就是Java健全的地方。
    事实上,几乎所有多线程应用都可用runnable接口方式。
    每个线程打印10遍这样重复50遍的话,就需要用synchronized关键字让两个线程同步,这里面需要用到线程等待和给予另外一个线程启动的对象。
    代码的话,你自己找个视频研究一下就明白了。
    视频推荐张孝祥的,他讲的很清楚。