第一种方法:
public class FirstThread extends Thread{
public void run() {
for(int i=0; i<1000; i++){
System.out.println(i);
}
}
}
public class Test {
public static void main (String args[]){
FirstThread firstThread = new FirstThread();
firstThread.start();
for(int i=0; i<1000; i++){
System.out.println(i);
}
}
}
第二种方法:
public class RunnableIml implements Runnable{
public void run() {
for(int i=0; i<100; i++){
System.out.println("Runnable->" + i);
}
}
}
public class Test1 {
public static void main(String args[]){
RunnableIml runnable = new RunnableIml();
Thread thread = new Thread(runnable);
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
for(int i=0; i<100; i++){
System.out.println("main->" + i);
if(i==60){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("优先级" + thread.getPriority());
}
}
Thread.sleep()休眠
getPriority()优先级
同步:
public class MyThread implements Runnable{
int i= 1000;
public void run() {
while(true){
synchronized (this) {
System.out.println(Thread.currentThread().getName() + i);
i--;
Thread.yield();
if(i<0){
break;
}
}
}
}
}
public class Test2 {
public static void main(String args[]){
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread);
Thread thread2 = new Thread(myThread);
thread1.setName("线程a");
thread2.setName("线程b");
thread1.start();
thread2.start();
}
}
Thread.currentThread()获得当前线程
synchronized 线程锁