多线程-java

继承Thread

public class ThreadTest extends Thread{
    
    private ThreadTestMain test;
    //private ThreadTestJunit test;
@Override
public void run(){ synchronized (this){ if(test.student_number_op>0){ Date date = new Date(); long time1 = new Date().getTime(); System.out.println(Thread.currentThread().getName()+"打了一份饭,还剩下"+--test.student_number_op+"个学生没有打,现在的时间是"+time1); } } } }

实现Runnable接口,

Runnable是接口,Thread是类,Thread类实现了Runnable接口,

Runnable与Thread避免了继承的局限,一个类可以实现多个接口,只能继承一个类;

继承了Thread就无法继承其他类

public class RunnableTest implements Runnable{
    
    private ThreadTestMain test;
    //private ThreadTestJunit test;
@Override
public void run(){ synchronized (this){ if(test.student_number_op>0){ Date date = new Date(); long time1 = new Date().getTime(); System.out.println(Thread.currentThread().getName()+"打了一份饭,还剩下"+--test.student_number_op+"个学生没有打,现在的时间是"+time1); } } } }

main,

public class ThreadTestMain {
    
    public static final int Thread_Number = 100;
    public static final int Student_Number = 1000;
    public static int student_number_op = Student_Number;
public static int thread_number_op = Thread_Number;
public static ThreadTest ThreadTest = new ThreadTest(); public static RunnableTest RunnableTest = new RunnableTest(); public static void main(String[] args) { // TODO Auto-generated method stub int i = 0; while (thread_number_op>0) { new Thread(ThreadTest, ++i+"号饭堂窗口").start();
//new Thread(RunnableTest, ++i+"号饭堂窗口").start();
i++;
thread_number_op--;
}
}
}

 Junit,电脑不好操作要谨慎,会卡死;

 Junit不会等待所有线程都执行完才结束,多线程测试还是用main比较靠谱

public class ThreadTestJunit extends Thread{
    
    public static final int Thread_Number = 100;
    public static final int Student_Number = 1000;
    public static int student_number_op = Student_Number;
    public static ThreadTest ThreadTest = new ThreadTest();
    public static RunnableTest RunnableTest = new RunnableTest();
    
    @Before
    public void setUp() throws Exception {
        student_number_op = Student_Number;
    }

    @After
    public void tearDown() throws Exception {
        
    }

    @Test
    public void test1() {
        
        int i = 0;
        while (student_number_op>0) {
            new Thread(ThreadTest, ++i+"号饭堂窗口").start();
            i++;
        }
    }
    
    @Test
    public void test2() {
        
        int i = 0;
        while (student_number_op>0) {
            new Thread(ThreadTest, ++i+"号饭堂窗口").start();
            i++;
        }
    }

}

 

posted on 2017-10-10 10:56  研者  阅读(212)  评论(0编辑  收藏  举报