Java multi-threading of Thread VS Runnable

Thread VS Runnable

Comparison of two ways:

  • Thread Runnable way to avoid defects due to the way Java's single inheritance characteristics brought
  • Runnable code may be a plurality of threads (Thread example) share for processing a plurality of threads where the same resource. (Refer to the same resource with a Runnable object)
  • Secure ticketing procedures need to add synchronous (Synchronized)
class MyThread extends Thread{
	private int tickets=5;
	private String name;//窗口,也是线程的名字
	
	public MyThread(String name) {
		super();
		this.name = name;
	}
	
	@Override
	public void run() {
		while(tickets > 0) {
			tickets--;
			System.out.println(name+"卖了1张票,剩余票数:"+tickets);
		}
	}
}

public class TicketsThread{
//共卖了15张票
	public static void main(String[] args) {
		//创建三个线程,模拟三个窗口卖票
		MyThread mt1 = new MyThread("窗口1");
		MyThread mt2 = new MyThread("窗口2");
		MyThread mt3 = new MyThread("窗口3");
				
		//启动三个线程,开始卖票
		mt1.start();
		mt2.start();
		mt3.start();
	}

}

class MyThread implements Runnable{
	private int tickets=5;
	
	@Override
	public void run() {
		while(tickets > 0) {
			tickets--;
			System.out.println(Thread.currentThread().getName()+"卖了1张票,剩余票数:"+tickets);
		}
	}
}

public class TicketsRunnable {

	public static void main(String[] args) {
		MyThread mt = new MyThread();
		//创建三个线程来模拟三个售票窗口
		Thread t1=new Thread(mt,"窗口1");
		Thread t2=new Thread(mt,"窗口2");
		Thread t3=new Thread(mt,"窗口3");
		
		//说明三个窗口各卖5张票
/*		MyThread mt1 = new MyThread();
		MyThread mt2 = new MyThread();
		MyThread mt3 = new MyThread();
		//创建三个线程来模拟三个售票窗口
		Thread t1=new Thread(mt1,"窗口1");
		Thread t2=new Thread(mt2,"窗口2");
		Thread t3=new Thread(mt3,"窗口3");*/
		
		t1.start();
		t2.start();
		t3.start();
	}
}

Summary : create multi-threaded Runnable use in this way.

Thread life cycle and thread guard

Thread of the life cycle
Thread of the life cycle:

  • Ready: After creating a thread object, the thread calls the start () method (Note: At this point only the thread into the thread queue, waiting to acquire CPU service, with the conditions of operation, but not necessarily is up and running)

  • Run: thread is ready, once acquired CPU resources, will enter the run state, started run () method inside the logic.

  • Termination: run the thread () method is finished, or thread calls the stop () method (this method was eliminated out), the thread will enter the final state.

  • Obstruction: a thread being executed in some cases, for some reason temporarily give up CPU resources, to suspend their execution, will enter the blocked state, such as calling the sleep () method.
    Java threads There are two types :

  • User thread: in the foreground, to perform specific tasks

    • The main thread, connected to the network are all child threads user thread.
  • Daemon thread: running in the background, foreground thread for other services

    • Features: Once all the end user threads are running, with the end of daemon threads will work with the JVM.
    • Applications:
      database connection pool monitoring thread
      monitor JVM thread after the virtual machine starts
      most common thread guard: garbage collection thread
  • How to set daemon thread:

    • The current may be set as a daemon thread by thread setDaemon Thread class (true) method
    • note:
      • setDaemon (true) must be called before start () method, otherwise it will throw an exception IllegalThreadStateException
      • New thread produced in the daemon thread is a daemon thread
      • Not all of the tasks can be assigned to the daemon thread to execute, such as read and write operations or calculation logic
/**
 * 模拟: 守护线程:很长一段时间向文件中写数据
 * 		主线程:会阻塞等待来自键盘的输入,一旦获取用户的输入阻塞解除,主线程继续运行,直到结束(守护线程也会随JVM一起结束运行)。
 */
class DaemonThread implements Runnable{
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("进入守护线程:"+Thread.currentThread().getName());
		try {
			writeToFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("退出守护线程:"+Thread.currentThread().getName());
	}

	private void writeToFile() throws Exception{
		File filename = new File("daemon.txt");
		OutputStream os = new FileOutputStream(filename,true);
		int count=0;
		while(count <99) {
			os.write(("\r\nword"+count).getBytes());
			System.out.println("守护线程"+Thread.currentThread().getName()
					+"向文件中写入了word"+count++);
			Thread.sleep(1000);
		}
	}
}

public class DaemonThreadDemo {

	public static void main(String[] args) {
		System.out.println("进入主线程"+Thread.currentThread().getName());
		DaemonThread dt = new DaemonThread();
		Thread t = new Thread(dt);
		t.setDaemon(true);
		t.start();
		
		Scanner sc = new Scanner(System.in);
		sc.next();
 		System.out.println("退出了主线程"+Thread.currentThread().getName());
	}

}

Published 13 original articles · won praise 11 · views 229

Guess you like

Origin blog.csdn.net/wangailin666/article/details/105128975
Recommended