1、编写一个ThreadTest类,分别通过继承Thread类和实现Runnable接口,两种方式实现两个线程。两个线程执行的任务是实现同一个变量 count 的累操作,count从1增加到10,每增加1, 在控制台输出 " 执行累加操作的线程的线程名+count 变量的值,输出后该线程 休眠1秒。在主方法中测试线程操作的相关方法(包括 sleep,interrupt,join)
我只会用sleep,其他两个不会用,完成学校的作业罢了,不要向我学习
package theme7_1;
public class ThreadTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread1 t1 = new MyThread1();
t1.setName("线程t1");
t1.start();
MyThread2 rt = new MyThread2();
Thread t2 = new Thread(rt);
t2.setName("线程t2");
t2.start();
}
}
//继承Thread类来实现线程
class MyThread1 extends Thread{
public void run() {
int count = 0;
for(int i=0; i<10; i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count+=1;
System.out.println(Thread.currentThread().getName()+" count="+count);
}
}
}
//实现Runnable接口来实现线程
class MyThread2 implements Runnable{
@Override
public void run() {
int count = 0;
for(int i=0; i<10; i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count+=1;
System.out.println(Thread.currentThread().getName()+" count="+count);
}
}
}