public class MultiThreadingTest1 {
public static void main(String[] args) {
MyThread1 myThread = new MyThread1();
myThread.start();
//如果直接调用run方法不属于多线程,因为没有开启新线程
//myThread.run();
//同一个新线程的对象不能重复start启动,如想重新启动新线程,需要创建一个新的对象
//myThread.start();//运行报错:java.lang.IllegalThreadStateException
System.out.println("我是主线程");
//匿名子类写法创建多线程
new Thread() {
@Override
public void run() {
// 此线程执行需要执行的操作声明在run中
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println("我是匿名子类新线程");
}
}.start();
}
}
class MyThread1 extends Thread {
@Override
public void run() {
// 此线程执行需要执行的操作声明在run中
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println("我是新线程");
}
}
public class MultiTheadingTest2 {
public static void main(String[] args) {
MyThread2 myThread2 = new MyThread2();
Thread thread = new Thread(myThread2);
thread.start();
System.out.println("我是主线程");
//匿名写法
new Thread(
new Runnable() {
@Override
public void run() {
// 此线程执行需要执行的操作声明在run中
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println("我是匿名新线程");
}
}).start();
}
}
class MyThread2 implements Runnable{
@Override
public void run() {
// 此线程执行需要执行的操作声明在run中
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println("我是新线程");
}
}