Thread 接口和 Runnable 接口,资源共享
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| package com.demo;
public class ThreadTest { public static void main(String args[]) { MyThread a = new MyThread(); a.setMyThreadName("xiaoming");
a.setPriority(1); a.setPriority(Thread.MIN_PRIORITY); a.setPriority(Thread.MAX_PRIORITY);
a.start();
MyThread2 b = new MyThread2(); b.setMyThreadName("xiaohong"); new Thread(b).start(); new Thread(b).start();
new Thread(() -> { for (int i = 0; i < 100; i++) { System.out.println( i + ".xiaofang"); } }).start(); } }
class MyThread extends Thread{ private String name;
@Override public void run() { super.run(); for (int i = 0; i < 100; i++) { System.out.println( i + "." + this.name); } }
public void setMyThreadName(String name) { this.name = name; } }
class MyThread2 implements Runnable { private String name;
@Override public void run() { for (int i = 0; i < 100; i++) { System.out.println( i + "." + this.name); } }
public void setMyThreadName(String name) { this.name = name; } }
|
Callable 接口,返回值,名称,休眠
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package com.demo.callable; import java.lang.management.ManagementFactory; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask;
public class CallableTest { public static void main(String args[]) throws Exception { FutureTask ticket = new FutureTask(new Ticket()); new Thread(ticket).start(); System.out.println(ticket.get());
Mythread mt = new Mythread(); new Thread(mt, "线程y").start(); } }
class Ticket implements Callable<String> {
@Override public String call() throws Exception { for (int i = 0; i < 10; i++) { System.out.println("卖了" + i + "张票"); } return "票卖完了"; } }
class Mythread implements Runnable { @Override public void run() { for (int i = 0; i < 100; i++) { try { System.out.println(ManagementFactory.getRuntimeMXBean().getName()); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(i + "." + Thread.currentThread().getName()); } } }
|
线程锁