Thread theFirst = new Thread(myThread);
Thread theSecond = new Thread(myThread); 既然你在2个线程里使用了同一个myThread,那么当然有同步问题你为何不使用2哦 myThread和myThread2 呢? new 一个对象很复杂吗?
Thread theSecond = new Thread(myThread); 既然你在2个线程里使用了同一个myThread,那么当然有同步问题你为何不使用2哦 myThread和myThread2 呢? new 一个对象很复杂吗?
代码:class PrintCode implements Runnable{
public static void main(String[]args){ PrintCode print = new PrintCode(); }}
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);
}
}
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");
}
}
}
事实上,几乎所有多线程应用都可用runnable接口方式。
每个线程打印10遍这样重复50遍的话,就需要用synchronized关键字让两个线程同步,这里面需要用到线程等待和给予另外一个线程启动的对象。
代码的话,你自己找个视频研究一下就明白了。
视频推荐张孝祥的,他讲的很清楚。