JAVA_多线程之创建

THREAD

1 优先权 setPriority(PRIORITY) --> Thread.MIN_MAX_NORM_PRIORITY

2 线程的创建方式

  • 1
Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello\t"+ Thread.currentThread().getName());
                }
            });
            thread.start();
  • 2
public class MultiThread {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
public class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("hello \t , " + Thread.currentThread().getName());
    }
}
  • 3 两个线程共用一个Runnable实现的对象
//实现Runnable接口的类
public class MyThread implements Runnable{
    int resources = 100;
    @Override
    public void run() {
        while(resources>=0) {
            if (Thread.currentThread().getName().equals("1")) {
                resources = resources - 1;
                System.out.println("resources : " + resources + "\t used by " + Thread.currentThread().getName());

            }
            if (Thread.currentThread().getName().equals("2")) {
                resources = resources - 2;
                System.out.println("resources : " + resources + "\t used by " + Thread.currentThread().getName());
            }
        }
    }
}
//共用一个实现了Runnable接口的类
public class MultiThread {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread one = new Thread(myThread);
        Thread two = new Thread(myThread);
        one.setName("1");
        two.setName("2");
        one.start();
        two.start();
    }
}

猜你喜欢

转载自blog.csdn.net/ahao6666666/article/details/121664527
今日推荐